猫鼬-查询深度嵌套的对象 [英] Mongoose - Query deeply nested Objects
本文介绍了猫鼬-查询深度嵌套的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前遇到一个问题,我必须更新深层嵌套文档中的条目。现在简化我的问题,我有这个例子。假设我将汽车存储在MongoDB中。文档看起来像这样
I currently have a problem where I have to update entries in a deeply nested Document. Now to simplify my problem I have this example. Let's assume I store cars in my MongoDB. A Document would look like this
{
Make: "BMW",
Model: "3Series",
Wheels: [
{
_id: someObjectId
Size: "19 inch",
Screws: [
{
_id: someObjectId
Type : "M15x40"
},
{
_id: someObjectId
Type : "M15x40"
}
]
}
]
}
现在,如果我想更新特定的Wheel,我的代码看起来像这样
Now if I want to update a specific Wheel, my code would look somewhat like this
CarModel.findOneAndUpdate({
"_id": CarId, "Wheels._id": WheelId
}, {
"$set" : {
"Wheels.$.Size": NewSize
}
})
现在可以使用了。但是当我经历2个数组时,我对如何更新特定的螺丝感到非常迷惑。知道我该怎么做吗?
Now this works. But I am pretty lost on how I would update an specific screw as I am going through 2 Arrays. Any Idea how I could make this work?
推荐答案
您需要 arrayFilters 功能来定义多个嵌套数组的路径:
You need arrayFilters functionality to define the path for more than one nested array:
CarModel.findOneAndUpdate(
{ "_id": CarId },
{ $set: { "Wheels.$[wheel].Screws.$[screw].Type": "something" } },
{ arrayFilters: [ { 'wheel._id': WheelId }, { 'screw._id': screwId } ] })
这篇关于猫鼬-查询深度嵌套的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文