简体   繁体   English

收集字段中的流星计算值

[英]Meteor Calculated Value in Collection Field

Is there a way to have a allways calculated value in Meteor collection field? 有没有一种方法可以在Meteor收集字段中获得始终计算的值? I am currently developing an app to manage inventory of sandwiches. 我目前正在开发一个用于管理三明治库存的应用。 Each sandwich can depend on ingredients in other collections. 每个三明治都可以取决于其他系列的成分。 I need to have a field always auto calculated to the number of the ingredient that is lowest in stock. 我需要一个字段始终自动计算为库存中最低的成分数。 How can i achieve this? 我怎样才能做到这一点? I can not find anything about this when I Google, is it possible that Meteor does not have any support for this? 我在Google上找不到任何相关信息,Meteor是否可能对此没有任何支持?

This sounds like a job for a collection hook . 这听起来像是收集挂钩的工作 Collection hooks allow you to execute an action before/after collections are inserted/updated/etc. 集合挂钩允许您在插入/更新集合等之前/之后执行操作。

Let's say you have an ingredients collection. 假设您有一个食材收藏。 Perhaps that ingredients collection has a schema like: 也许该成分集合具有类似以下的模式:

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

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

Ingredients.attachSchema(IngredientsSchema);

Then you have a sandwiches collection with a hypothetical schema: 然后,您将获得一个带有假设模式的三明治集合:

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);

Your collection hook would be something along the lines of: 您的收藏夹将类似于以下内容:

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 });
  } 
});

You'll probably also need a collection hook after inserting an ingredient, but this should be plenty to get you started. 插入成分后,您可能还需要一个收集钩,但这应该足以帮助您入门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM