猫鼬,更新对象数组中的值
问题描述:
是否可以更新对象中的值?
Is there a way to update values in an object?
{
_id: 1,
name: 'John Smith',
items: [{
id: 1,
name: 'item 1',
value: 'one'
},{
id: 2,
name: 'item 2',
value: 'two'
}]
}
让我们说我想为id = 2的项更新名称和值项.
Lets say I want to update the name and value items for item where id = 2;
我尝试了以下搭配猫鼬的东西:
I have tried the following w/ mongoose:
var update = {name: 'updated item2', value: 'two updated'};
Person.update({'items.id': 2}, {'$set': {'items.$': update}}, function(err) { ...
这种方法的问题是它会更新/设置整个对象,因此在这种情况下,我会丢失id字段.
Problem with this approach is that it updates/sets the entire object, therefore in this case I lose the id field.
猫鼬中是否有更好的方法来设置数组中的某些值,而不管其他值?
Is there a better way in mongoose to set certain values in an array but leave other values alone?
我也只查询了这个人:
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().
});
答
您已经关闭;在使用 $
更新运算符href href ="https://docs.mongodb.com/manual/reference/operator/update/positional/" >为此:
You're close; you should use dot notation in your use of the $
update operator to do that:
Person.update({'items.id': 2}, {'$set': {
'items.$.name': 'updated item2',
'items.$.value': 'two updated'
}}, function(err) { ...