Mongoose,更新对象数组中的值 [英] Mongoose, update values in array of objects
本文介绍了Mongoose,更新对象数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法更新对象中的值?
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.
在 mongoose 中是否有更好的方法来设置数组中的某些值但不考虑其他值?
Is there a better way in mongoose to set certain values in an array but leave other values alone?
我也只查询了 Person:
I have also queried for just the Person:
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().
});
推荐答案
你已经接近了;您应该在使用 $
时使用点表示法更新运算符来做到这一点:
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) { ...
这篇关于Mongoose,更新对象数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文