如何更新数组中的嵌套对象(Mongoose/MongoDB)

How to update nested object in array (Mongoose/MongoDB)

提问人:Ope Afolabi 提问时间:8/22/2022 更新时间:8/22/2022 访问量:260

问:

我一直在努力弄清楚如何使用特定 id 更新嵌套数组中的对象。我尝试实现$set如下所示。我希望能够使用请求正文中的数据以 62ff74bfe80b11ade2d34455 _id更新任务。

{
    "_id": "62fa5aa25778ec97bc6ee231",
    "user": "62f0eb5ebebd0f236abcaf9d",
    "name": "Marketing Plan",
    "columns": [
        {
            "name": "todo",
            "_id": "62fa5aa25778ec97bc6ee233",
            "tasks": [
                {           ====> here
                    "title": "Task Four",
                    "description": "This is task four",
                    "subtasks": [
                        {
                            "name": "wash dshes",
                            "completed": false,
                            "_id": "62ff74bfe80b11ade2d34456"
                        },
                        {
                            "name": "do homework",
                            "completed": false,
                            "_id": "62ff74bfe80b11ade2d34457"
                        }
                    ],
                    "_id": "62ff74bfe80b11ade2d34455"
                }
            ]
        },
        {
            "name": "doing",
            "_id": "62fa5aa25778ec97bc6ee234",
            "tasks": []
        },
        {
            "name": "done",
            "_id": "62fa5aa25778ec97bc6ee235",
            "tasks": []
        }
    ],
    "__v": 0
}
    const updatedTask = await Board.findOneAndUpdate(
        {
          "columns.tasks._id": req.params.id,
        },
        { $set: { "columns.$.tasks": req.body } },
        { new: true }
      );
JavaScript 节点.js Express Mongoose

评论


答:

2赞 eol 8/22/2022 #1

您可以将位置运算符与 arrayfilter 结合使用。以下示例介绍了如何更新相关任务的特定字段:

db.collection.update({
  "columns.tasks._id": req.params.id
},
{
  "$set": {
    "columns.$[].tasks.$[t].title": "it works"
  }
},
{
  "arrayFilters": [
    {
      "t._id": req.params.id
    }
  ]
})

您也可以在 mongoplayground 上尝试此操作。

如果你正在寻找一种方法来替换匹配的任务对象本身,你可以这样做:

db.collection.update({
      "columns.tasks._id": req.params.id
    },
    {
      "$set": {
        "columns.$[].tasks.$[t]": req.body
      }
    },
    {
      "arrayFilters": [
        {
          "t._id": req.params.id
        }
    ]
})