2013-03-28 113 views
41

有沒有辦法更新對象中的值?Mongoose,更新對象數組中的值

{ 
    _id: 1, 
    name: 'John Smith', 
    items: [{ 
    id: 1, 
    name: 'item 1', 
    value: 'one' 
    },{ 
    id: 2, 
    name: 'item 2', 
    value: 'two' 
    }] 
} 

可以說我想更新項目的名稱和值項目,其中id = 2;

我曾嘗試以下w /貓鼬:

var update = {name: 'updated item2', value: 'two updated'}; 
Person.update({'items.id': 2}, {'$set': {'items.$': update}}, function(err) { ... 

問題這種方法是,它更新/設置整個對象,因此在這種情況下,我失去了id字段。

有沒有更好的方法在貓鼬中設置數組中的某些值,但只保留其他值?

我也查詢了剛剛的人:

Person.find({...}, function(err, person) { 
    person.items ..... // I might be able to search through all the items here and find item with id 2 then update the values I want and call person.save(). 
}); 

回答

72

你靠近;你應該使用點符號在$set做到這一點:

Person.update({'items.id': 2}, {'$set': { 
    'items.$.name': 'updated item2', 
    'items.$.value': 'two updated' 
}}, function(err) { ... 
+0

你好,當我完全按照你的建議。 board.update({_id:board._id,「users.username」:req.user.username},{$ set:{「users。$。lastViewed」:new Date()}},function(err){ }); 我得到一個錯誤: 不能使用部分(users.username的用戶)來遍歷元素({users:[{username:「nlm」,_id:ObjectId('583c8cc3813daa6c29f69cb0'),status:「invited」,role :「reviewer」}]})。我有什麼不同嗎? – sh977218

+2

這很好,謝謝。 但是,有沒有什麼辦法可以創建一個項目,如果它不在數組中? –

4

對於每一個文檔,更新操作$set可以set multiple values,因此而不是替換items數組中的整個對象,你可以設置namevalue領域的對象。

{'$set': {'items.$.name': update.name , 'items.$.value': update.value}} 
+0

太棒了,生病明天就試試。非常感謝! – lostintranslation

0

在貓鼬,我們可以在下面的方式

db.collection.update({"_id": args._id, "viewData._id": widgetId}, {$set: {"viewData.$.widgetData": widgetDoc.widgetData}}) 
+0

請您編輯答案和解釋,或者與問題有關嗎? –

+0

這是你如何在mongodb中更新它? –

0
model.update({"_id": 1, "items.id": "2"}, 
{$set: {"items.$.name": "yourValue","items.$.value": "yourvalue"}}) 

Mongodb document

0

在貓鼬我們可以更新更新使用$set內圓點(.)符號到特定值數組值,像簡單的陣列

user.updateInfoByIndex(0,"test") 

User.methods.updateInfoByIndex = function(index, info) ={ 
    this.arrayField[index]=info 
    this.save() 
} 
+1

你的回答對於一些解釋會更有幫助。請考慮編輯它。 –

相關問題