【问题标题】:how to make a temporary collection in meteor?如何在流星中进行临时收藏?
【发布时间】:2015-03-30 13:51:31
【问题描述】:

作为前言:我对 Meteor 还很陌生。

我的目标:我正在尝试创建一个网站,将蔬菜存储为一个集合,将食谱(包含所需的成分)存储为一个集合,并根据用户是否有用户已勾选的成分。只会显示包含勾选成分的食谱。

为此,我想创建一个包含选中标记成分的临时集合,并使用它来识别要显示的食谱。我尝试使用会话,但我不知道是否可以从会话中插入/删除和查找项目,所以我更喜欢使用集合。但是,如果多个用户同时使用该网站,我不希望集合受到干扰,因此我希望集合对每个访问者都是唯一的(客户端和临时的,如 sesson)

到目前为止,我有以下代码:

展示蔬菜的模板:

<template name="veggies">
  <ul>
    {{#each vegetables}}
      <li class="{{#if checked}}checked{{/if}}">
        <input type="checkbox" checked="{{checked}}" class="toggle-checked" />
        <span class="text">{{vegetable}}</span>
      </li>
    {{/each}}
  </ul>
</template>

<template name="button">
  <button class="submit">Sugest recipes</button>
</template>

蔬菜的Javascript文件代码:

Recipes = new Mongo.Collection('recipes');
vegetables = new Mongo.Collection('vegetable');


if (Meteor.isClient) {


// VEGGIES

  // this displays the vegetables
  Template.veggies.helpers({
    'vegetables': function() {
      return vegetables.find()
    }

  });

  // this selects toggles the check mark
  Template.veggies.events({
    "click .toggle-checked": function () {
      this._id, {$set: {checked: ! this.checked}};
      var ItemID = this._id
      Session.set('selectedVeggies', ItemID);
    },
  });

  // this submits the request and reveals possible recipes
  Template.button.events({
    "click .submit": function () {
      Session.set('PossibleRecipes', true);
    }
  });

所以 - 我需要知道是否有办法完成这项任务。我可以将所有成分硬编码为布尔变量,然后根据哪些布尔值为真显示可能的食谱,但这似乎很耗时,我宁愿创建一个动态系统,其中蔬菜/成分列表和食谱可以很容易地添加/减去。

【问题讨论】:

    标签: javascript mongodb meteor spacebars


    【解决方案1】:

    您可以使用仅限客户端的集合。详细阅读我的文章:http://meteor.hromnik.com/blog/array-of-objects-as-a-client-side-collection-in-meteor

    【讨论】:

      【解决方案2】:

      要创建客户端集合,不要给它一个名称参数。

      // This collection has a name, and will work on both the server and client
      Recipes = new Mongo.Collection('recipes');
      
      // This collection is client-only, and does not have a name.
      // It will not be synchronized with the server.
      Vegetables = new Mongo.Collection();
      
      // To be more explicit, you can use `null` for the name:
      Meats = new Mongo.Collection(null);
      

      【讨论】:

      • 感谢您的解释。现在我的第二个问题是:是否可以将从一个集合复制的文档插入到另一个集合中?
      • 你的意思是:Collection1.insert(Collection2.findOne());
      • 我创建了一个名为 CheckedVeggies 的客户端集合: CheckedVeggies = new Mongo.Collection('null'); Template.veggies.events({ "click .toggle-checked": function () { this._id, {$set: {checked: !this.checked}}; var ItemID = this._id; CheckedVeggies.insert(vegetables. find({vegetable: ItemID}).fetch()); }, });这似乎不起作用
      • @SamLouisMilligan collection.insert 方法需要一个文档。您需要使用 cursor.forEach 遍历游标并将每个文档插入游标中,而不是获取。
      猜你喜欢
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 2015-04-19
      相关资源
      最近更新 更多