node.js Mongoose,更新对象数组中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15691224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongoose, update values in array of objects
提问by lostintranslation
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'
}]
}
Lets say I want to update the name and value items for item where id = 2;
假设我想更新 id = 2 项的名称和值项;
I have tried the following w/ mongoose:
我已经尝试了以下 w/猫鼬:
var update = {name: 'updated item2', value: 'two updated'};
Person.update({'items.id': 2}, {'$set': {'items.$': update}}, function(err) { ...
Problem with this approach is that it updates/sets the entire object, therefore in this case I lose the id field.
这种方法的问题在于它更新/设置整个对象,因此在这种情况下我丢失了 id 字段。
Is there a better way in mongoose to set certain values in an array but leave other values alone?
在 mongoose 中是否有更好的方法来设置数组中的某些值但不考虑其他值?
I have also queried for just the Person:
我也只查询了 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().
});
回答by JohnnyHK
You're close; you should use dot notation in your use of the $update operatorto do that:
你很近;您应该在使用$更新运算符时使用点符号来做到这一点:
Person.update({'items.id': 2}, {'$set': {
'items.$.name': 'updated item2',
'items.$.value': 'two updated'
}}, function(err) { ...
回答by Howard
model.update({"_id": 1, "items.id": "2"},
{$set: {"items.$.name": "yourValue","items.$.value": "yourvalue"}})
回答by Shaun
For each document, the update operator $setcan set multiple values, so rather than replacing the entire object in the itemsarray, you can set the nameand valuefields of the object individually.
对于每个文档,更新操作符$set可以设置多个值,因此items您可以单独设置对象的name和value字段,而不是替换数组中的整个对象。
{'$set': {'items.$.name': update.name , 'items.$.value': update.value}}
回答by Anees Hameed
There is a mongoose way for doing it.
有一种猫鼬方法可以做到这一点。
const itemId = 2;
const query = {
item._id: itemId
};
Person.findOne(query).then(doc => {
item = doc.items.id(itemId );
item["name"] = "new name";
item["value"] = "new value";
doc.save();
//sent respnse to client
}).catch(err => {
console.log('Oh! Dark')
});
回答by Gopal Sharma
There is one thing to remember, when you are searching the object in array on the basis of more than one condition then use $elemMatch
有一件事要记住,当您根据多个条件搜索数组中的对象时,请使用$elemMatch
Person.update(
{
_id: 5,
grades: { $elemMatch: { grade: { $lte: 90 }, mean: { $gt: 80 } } }
},
{ $set: { "grades.$.std" : 6 } }
)
here is the docs
这是文档
回答by Jakub A Suplicki
Below is an example of how to update the value in the array of objects more dynamically.
下面是如何更动态地更新对象数组中的值的示例。
Person.findOneAndUpdate({_id: id},
{
"$set": {[`items.$[outer].${propertyName}`]: value}
},
{
"arrayFilters": [{ "outer.id": itemId }]
},
function(err, response) {
...
})
Note that by doing it that way, you would be able to update even deeper levels of the nested array by adding additional arrayFilterslike so:
请注意,通过这样做,您将能够通过添加如下附加内容来更新嵌套数组的更深层次arrayFilters:
"$set": {[`items.$[outer].innerItems.$[inner].${propertyName}`]: value}
"arrayFilters":[{ "outer.id": itemId },{ "inner.id": innerItemId }]
I hope it helps. Good luck!
我希望它有帮助。祝你好运!
回答by Chaitanya Adesara
update(
{_id: 1, 'items.id': 2},
{'$set': {'items.$[]': update}},
{new: true})
Here is the doc about $[]: https://docs.mongodb.com/manual/reference/operator/update/positional-all/#up.S[]
这是关于$[]:https: //docs.mongodb.com/manual/reference/operator/update/positional-all/#up的文档。小号[]
回答by Pedro JR
Having tried other solutions which worked fine, but the pitfall of their answers is that only fields already existing would update adding upsert to it would do nothing, so I came up with this.
尝试过其他工作正常的解决方案,但他们的答案的缺陷是只有已经存在的字段才会更新,向它添加 upsert 不会做任何事情,所以我想出了这个。
Person.update({'items.id': 2}, {$set: {
'items': { "item1", "item2", "item3", "item4" } }, {upsert:
true })
回答by KARTHIKEYAN.A
In Mongoose, we can update array value using $setinside dot(.) notation to specific value in following way
在 Mongoose 中,我们可以通过以下方式使用$set内部 dot( .) 表示法将数组值更新为特定值
db.collection.update({"_id": args._id, "viewData._id": widgetId}, {$set: {"viewData.$.widgetData": widgetDoc.widgetData}})
回答by Vilintritenmert
In mongoose we can update, like simple array
在猫鼬我们可以更新,就像简单的数组
user.updateInfoByIndex(0,"test")
User.methods.updateInfoByIndex = function(index, info) ={
this.arrayField[index]=info
this.save()
}

