问题:Mongoose,更新对象数组中的值

有没有办法更新对象中的值?

{
  _id: 1,
  name: 'John Smith',
  items: [{
     id: 1,
     name: 'item 1',
     value: 'one'
  },{
     id: 2,
     name: 'item 2',
     value: 'two'
  }]
}

假设我想更新 id u003d 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().
});

解答

你很近;您应该在使用$更新运算符时使用点符号来做到这一点:

Person.update({'items.id': 2}, {'$set': {
    'items.$.name': 'updated item2',
    'items.$.value': 'two updated'
}}, function(err) { ...
Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐