简体   繁体   中英

Meteor Calculated Value in Collection Field

Is there a way to have a allways calculated value in Meteor collection field? 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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