简体   繁体   中英

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

I'm making a kanban task management app and I'm trying to remove a task with the _id: req.params.id which has the value of 62fa5ae05778ec97bc6ee23a. I tried the following:

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

But I get the error Too many positional (ie '$') elements found in path'columns.$.tasks.$._id'

I searched for a while and came across arrayFilters from the docs but I'm struggling a lot to understand how to implement it for this particular need.

{
    "_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
}

You need to use $[] positional operator in order to pull from the nested array. Try running this query:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM