有没有办法更新对象中的值?
{
_id: 1,
name: 'John Smith',
items: [{
id: 1,
name: 'item 1',
value: 'one'
},{
id: 2,
name: 'item 2',
value: 'two'
}]
}
假设我想更新 id = 2 的项目的名称和值项目;
我已经尝试了以下 w/ Mongoose :
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().
});
最佳答案
你很接近;您应该在使用 $
update operator 时使用点符号这样做:
Person.update({'items.id': 2}, {'$set': {
'items.$.name': 'updated item2',
'items.$.value': 'two updated'
}}, function(err) { ...
https://stackoverflow.com/questions/15691224/