[英]Mongoose: Find parent and update nested 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"
}
]
}
]
在这个 object 中,我需要:
_id
查找item
尝试的解决方案
我尝试使用aggregate
,但我只能找到 object,而不是修改它:
const ObjectId = mongoose.Types.ObjectId;
const item = await UserModel.aggregate([
{ $unwind: "$items" },
{
$match: { store, "items._id": ObjectId("1_1") },
},
]);
期望的结果
如何按store
查找商品,然后按_id
查找商品子项,最后更改找到的item
的名称?
先感谢您!
在store
和items._id
中,您放置要搜索的变量。 $set
在此处更改名称。
这适用于 1 级嵌套数组。 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"
}
}
);
看看这是否有效
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.