[英]Mongoose: Find parent and update nested object
Problem问题
I have the following object:我有以下 object:
[
{
"_id":"1",
"store":"llama.com",
"items":[
{
"_id":"1_1",
"name":"item1"
},
{
"_id":"1_2",
"name":"item2"
}
]
},
{
"_id":"2",
"store":"frog.com",
"items":[
{
"_id":"2_1",
"name":"item1"
},
{
"_id":"2_2",
"name":"item2"
}
]
}
]
In this object, I need to:在这个 object 中,我需要:
item
by _id
_id
查找item
Solutions tried尝试的解决方案
I tried using aggregate
but I'm only able to find the object, not modify it:我尝试使用
aggregate
,但我只能找到 object,而不是修改它:
const ObjectId = mongoose.Types.ObjectId;
const item = await UserModel.aggregate([
{ $unwind: "$items" },
{
$match: { store, "items._id": ObjectId("1_1") },
},
]);
Desired outcome期望的结果
How can I find an item by store
, then find the item child by _id
and finally change the name of the found item
?如何按
store
查找商品,然后按_id
查找商品子项,最后更改找到的item
的名称?
Thank you in advance!先感谢您!
In the store
and items._id
you put your variables that you want to search.在
store
和items._id
中,您放置要搜索的变量。 $set
changes the name here. $set
在此处更改名称。
This works for 1 level nested array.这适用于 1 级嵌套数组。 For deeper nested arrays you should go with
arrayFilters
https://docs.mongodb.com/manual/release-notes/3.6/#arrayfilters For deeper nested arrays you should go with
arrayFilters
https://docs.mongodb.com/manual/release-notes/3.6/#arrayfilters
const item = await UserModel.findOneAndUpdate(
{
store: "some store",
"items._id": "your id"
},
{
$set: {
[`items.$.` + variable]: "change your name"
}
}
);
See if this works看看这是否有效
const item = await UserModel.findOneAndUpdate({ "store": "storeName",
"items._id" : "id" },{$set:{"items.0.name":"itemName"}}, {new: true})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.