2012-09-12 46 views
25

使用流星,我想執行類似下面的更新:使用MongoDB中更新變量

Items.update(Session.get('selectedItem'), {'$set': {'directions.0.name': area.value}}) 

但我有如何動態地設置方向的數組索引,喜歡的東西掙扎這個:

var index = //a value determined dynamically 
Items.update(Session.get('selectedItem'), {'$set': {'directions[index]name': area.value}}) 

這不起作用,因爲[index]被包裝在一個字符串中。我也試圖形成一個自定義的字符串,如下所示:

var string = 'directions.'+itemIndex+'.name' 
Items.update(Session.get('selectedItem'), {'$set': {string: area.value}}) 

但這並不奏效。任何想法如何做到這一點?

回答

48

您需要以編程方式建立你的$set對象:

var setModifier = { $set: {} }; 
setModifier.$set['directions.' + index + '.name'] = area.value; 
Items.update(Session.get('selectedItem'), setModifier); 

更新

如果你的JavaScript環境支持computed property names(如Node.js的4+),你可以在一個步驟做到這一點:

Items.update(Session.get('selectedItem'), { $set: { 
    ['directions.' + index + '.name']: area.value 
}}); 
+1

謝謝..這可能看起來很簡單,但我只是在學習mongodb。 – Goddard