有沒有辦法更新對象中的值?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().
});
你好,當我完全按照你的建議。 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
這很好,謝謝。 但是,有沒有什麼辦法可以創建一個項目,如果它不在數組中? –