集合域中的流星计算值

时间:2016-03-11 21:10:19

标签: javascript meteor

有没有办法在流星收集领域拥有一个总体计算值?我目前正在开发一个应用程序来管理三明治库存。每个三明治都可以依赖于其他系列中的成分。我需要一个字段总是自动计算出库存最低的成分数。我怎样才能实现这一目标?我在谷歌时找不到任何相关信息,Meteor是否有可能对此没有任何支持?

1 个答案:

答案 0 :(得分:1)

这听起来像collection hook的工作。集合挂钩允许您在插入/更新集合之前/之后执行操作。等等。

假设你有一个成分集合。也许该成分集合具有如下模式:

Ingredients = new Mongo.Collection('ingredients');

IngredientsSchema = new SimpleSchema({
  "name": {
    type: String
  },
  "quantity": {
    type: Number
  }
});

Ingredients.attachSchema(IngredientsSchema);

然后你有一个带有假设图式的三明治集合:

Sandwiches = new Mongo.Collection('sandwiches');

SandwichesSchema = new SimpleSchema({
  "name": {
    type: String
  },
  "ingredients": {
    type: [String],
    label: "An array of ingredient internal ids (_id)"
  },
  "quantity": {
    type: Number
  }
});

Sandwiches.attachSchema(SandwichesSchema);

你的收藏钩子将是:

Ingredients.after.update(function(userId, doc, fieldNames, modifier, options) {
  // Find the ingredient with the lowest value
  ingredient = Ingredients.findOne({}, { sort: { quantity: 1 } });
  if(ingredient && ingredient._id == doc._id) {
    //If the ingredient matches this ingredient, update all sandwiches who have the agreement to reflect the remaining quantity of ingredients.
    Sandwiches.update({ ingredients: doc._id }, { $set: { quantity: doc.quantity } }, { multi: true });
  } 
});

插入一种成分后,你可能还需要一个收集钩子,但这应该足以让你开始。

相关问题