2016-05-10 89 views
0

我在Meteor/MongoDB中將一組鍵值對相乘有問題。我想將整個成分列表乘以固定值。集合看起來是這樣的:MongoDB /流星:在集合中乘以整個陣列

"ingredients" : [ 
    { 
     "ingredient" : "noodle", 
     "amount" : 500, 
     "unit" : "g" 
    }, 
    { 
     "ingredient" : "cheese", 
     "amount" : 100, 
     "unit" : "g" 
    } 
], 

現在,我想有一定數量MULTIP乘以值,假設1,5。所需的輸出將如下所示:

"ingredients" : [ 
    { 
     "ingredient" : "noodle", 
     "amount" : 750, 
     "unit" : "g" 
    }, 
    { 
     "ingredient" : "cheese", 
     "amount" : 150, 
     "unit" : "g" 
    } 
], 

現在我有這樣的:

for (i in this.ingredients){ 
    var precalc = this.ingredients[i].amount * multip; //Here's the Multiplicator 
    var prez=this.ingredients[i].ingredient; 
    var prem=this.ingredients[i].unit; 
    Recipes.update(
    {"_id": this._id}, 
    {"$set": { 
     "ingredients":[{ingredient:prez, amount:precalc, unit:prem}] 
     }} 
); 
} 

我預先計算的新值,使用$設置,因爲顯然$ MUL操作者不與流星工作。此解決方案部分工作,但不幸的是它覆蓋所有成分,只增加最後一個(這是顯而易見的)。必須有一個更簡單的方法來做到這一點 - 我只是沒有找到它。我是MongoDB和Meteor的新手,非常感謝任何幫助!

+0

如何在循環後更新所有成分的集合(在循環過程中收集數組)? – MasterAM

回答

0

不要爲每個成分執行更新,只有一個用於整個文檔。我會做這樣的事情:

let newIngredients = this.ingredients.map(x => { 
    ingredient: x.ingredient, 
    amount: x.amount * 1.5, 
    unit: x.unit 
}); 

Recipes.update(
    {_id: this._id}, 
    {$set: {ingredients: newIngredients}} 
); 
+0

謝謝!我知道這很容易。不幸的是胖箭頭語法無法正常工作,但我最終創建了一個newIngredients數組並更新了Collection。完美的作品! –