[英]Meteor Calculated Value in Collection Field
有沒有一種方法可以在Meteor收集字段中獲得始終計算的值? 我目前正在開發一個用於管理三明治庫存的應用。 每個三明治都可以取決於其他系列的成分。 我需要一個字段始終自動計算為庫存中最低的成分數。 我怎樣才能做到這一點? 我在Google上找不到任何相關信息,Meteor是否可能對此沒有任何支持?
這聽起來像是收集掛鈎的工作 。 集合掛鈎允許您在插入/更新集合等之前/之后執行操作。
假設您有一個食材收藏。 也許該成分集合具有類似以下的模式:
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 });
}
});
插入成分后,您可能還需要一個收集鈎,但這應該足以幫助您入門。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.