gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:14:19 37 4
gpt4 key购买 nike

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

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

关于node.js - Mongoose,更新对象数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15691224/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com