如何删除深度嵌套对象(Node.js,猫鼬)

How to remove deeply nested object (Node.js, mongoose)

提问人:Ope Afolabi 提问时间:8/16/2022 更新时间:8/16/2022 访问量:40

问:

我正在制作一个看板任务管理应用程序,我正在尝试删除一个值为 62fa5ae05778ec97bc6ee23a 的任务。我尝试了以下方法:_id: req.params.id

const task = await Board.findOneAndUpdate(
    {
      "columns.tasks._id": req.params.id,
    },
    { $pull: { "columns.$.tasks.$._id": req.params.id } },
    { new: true }
  );

但是我得到错误Too many positional (i.e. '$') elements found in path'columns.$.tasks.$._id'

我搜索了一段时间,并从文档中发现了它,但我正在努力了解如何实现它以满足这种特殊需求。arrayFilters

{
    "_id": "62fa5aa25778ec97bc6ee231",
    "user": "62f0eb5ebebd0f236abcaf9d",
    "name": "Marketing Plan",
    "columns": [
        {
            "name": "todo",
            "_id": "62fa5aa25778ec97bc6ee233",
            "tasks": [
                {
                    "title": "Task Four",
                    "description": "This is task four",
                    "subtasks": [
                        {
                            "name": "wash dshes",
                            "completed": false,
                            "_id": "62fa5ae05778ec97bc6ee23b"
                        },
                        {
                            "name": "do homework",
                            "completed": false,
                            "_id": "62fa5ae05778ec97bc6ee23c"
                        }
                    ],
                    "_id": "62fa5ae05778ec97bc6ee23a"
                }
            ]
        },
        {
            "name": "doing",
            "_id": "62fa5aa25778ec97bc6ee234",
            "tasks": []
        },
        {
            "name": "done",
            "_id": "62fa5aa25778ec97bc6ee235",
            "tasks": []
        }
    ],
    "__v": 0
}
JavaScript 节点.js Express Mongoose

评论


答:

1赞 Dezzley 8/16/2022 #1

您需要使用位置运算符才能从嵌套数组中提取。尝试运行此查询:$[]

db.Board.updateOne({
    "_id" : "62fa5aa25778ec97bc6ee231",
}, {
    $pull: { 'columns.$[].tasks': { '_id': '62fa5ae05778ec97bc6ee23a' } }
});