猫鼬,更新对象数组中的值 [英] Mongoose, update values in array of objects

查看:59
本文介绍了猫鼬,更新对象数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以更新对象中的值?

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().
});

推荐答案

您已经关闭;在使用 $更新运算符为此:

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) { ...

这篇关于猫鼬,更新对象数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆