【发布时间】:2021-02-20 06:28:09
【问题描述】:
我有一个多级嵌套文档(它的动态和某些级别可能会丢失,但最多 3 个级别)。如果有的话,我想更新所有的子路由和子路由。该方案与任何 Windows 资源管理器中的情况相同,其中所有子文件夹的路由都需要在父文件夹路由发生更改时更改。例如。在下面的例子中,如果我在route=="l1/l2a"并且它的名字需要编辑为“l2c”,那么我将它的路线更新为route="l1/l2c,我将更新所有孩子的路线说"l1/l2c/l3a"。
{
"name":"l1",
"route": "l1",
"children":
[
{
"name": "l2a",
"route": "l1/l2a",
"children":
[
{
"name": "l3a",
"route": "l1/l2a/l3a"
}]
},
{
"name": "l2b",
"route": "l1/l2b",
"children":
[
{
"name": "l3b",
"route": "l1/l2b/l3b"
}]
}
]
}
目前我可以去一个点,我可以通过以下方式更改它的名称和路线:
router.put('/navlist',(req,res,next)=>{
newname=req.body.newName //suppose l2c
oldname=req.body.name //suppose l2a
route=req.body.route // existing route is l1/l2a
id=req.body._id
newroute=route.replace(oldname,newname); // l1/l2a has to be changed to l1/l2c
let segments = route.split('/');
let query = { route: segments[0]};
let update, options = {};
let updatePath = "";
options.arrayFilters = [];
for(let i = 0; i < segments.length -1; i++){
updatePath += `children.$[child${i}].`;
options.arrayFilters.push({ [`child${i}.route`]: segments.slice(0, i + 2).join('/') });
} //this is basically for the nested children
updateName=updatePath+'name'
updateRoute=updatePath+'route';
update = { $setOnInsert: { [updateName]:newDisplayName,[updateRoute]:newroute } };
NavItems.updateOne(query,update, options)
})
问题是我无法编辑它的孩子的路线(如果有的话),即它的子文件夹路线为l1/l2c/l3a。虽然我尝试如下使用$[] 运算符。
updateChild = updatePath+'.children.$[].route'
updateChild2 = updatePath+'.children.$[].children.$[].route'
//update = { $set: { [updateChild]:'abc',[updateChild2]:'abc' } };
关卡可自定义很重要,因此我不知道是否有“l3A”。就像可以有“l3A”但可能没有“l3B”。但我的代码只需要每条正确的路径,否则会出错
code 500 MongoError: The path 'children.1.children' must exist in the document in order to apply array updates.
所以问题是如何使用 $set 将更改应用到实际存在的路径以及如何编辑现有的路径部分。如果路径存在,那很好,如果路径不存在,我会收到错误消息。
【问题讨论】:
-
route:l1是唯一的吗? -
是的 l1 是唯一的。实际上名称和路线不必相同,但为简单起见,我保持它们相同。
标签: javascript node.js mongodb mongoose nosql