node.js - Mongoose,更新对象数组中的值

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

{
  _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/

相关文章:

javascript - MongoDB选择_id数组的位置?

linux - 连接被拒绝 MongoDB errno 111

mongodb - 在 Mongo 中,我如何漂亮地打印结果,所以 .find() 看起来像 .fi

javascript - 如何使用 node.js 连接到 mongodb(并进行身份验证)?

mongodb - MongoDB中的数据重复太多?

mongodb - 在 MongoDB 中是否有命名集合的约定?

mongodb - MongoDB 中的 $unwind 运算符是什么?

javascript - MongoDB,从数组中删除对象

mongodb - 如何在mongodb中查询子对象

javascript - 使用 Node.js 和 MongoDB 存储密码