【发布时间】:2013-03-19 10:40:50
【问题描述】:
有没有办法更新对象中的值?
{
_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 字段。
在 mongoose 中有没有更好的方法来设置数组中的某些值但不理会其他值?
我也只查询了这个人:
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().
});
【问题讨论】: