2016-05-10 6 views
0

Meteor/MongoDBでキーと値のペアの配列を掛けることに問題があります。私は成分リスト全体を固定値で掛けたい。コレクションは次のようになります。MongoDB/Meteor:コレクション内で配列全体を掛け合わせる

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

今、私はのは1,5を言わせて、一定数multip値を乗算します。所望の出力は次のようになります。私は、新しい値を事前に計算し、明らかに$ mulの演算子は流星で作業されていないため、設定$を使用

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

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

今、私はこれを持っています。この解決法は部分的には機能しますが、残念ながらすべての成分を上書きし、最後の成分のみを乗算します(明白です)。それを行うにはもっと簡単な方法が必要です - 私はそれを見つけられませんでした。私はMongoDBとMeteorを初めて使っているので、どんな助けでも大歓迎です!

+0

ループの後のすべての成分でコレクションを更新するとどうなりますか? – MasterAM

答えて

0

各成分の更新は実行しないでください。文書全体の更新は1つのみです。私は次のようなことをします:

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を一度更新することになりました。完璧に動作します! –

関連する問題