簡體   English   中英

如何更新 mongoose 中的嵌套 object?

[英]How to update nested object in mongoose?

我正在構建一個看板任務管理應用程序。 到目前為止,我已經能夠創建任務和刪除任務,但我可以了解如何更新嵌套任務 object。 我已經搜索了文檔,沒有明確的解釋。

我想用 62ff74bfe80b11ade2d34455 的 id 更新任務 - req.params.id 和 req.body。

{
    "_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": "62ff74bfe80b11ade2d34456"
                        },
                        {
                            "name": "do homework",
                            "completed": false,
                            "_id": "62ff74bfe80b11ade2d34457"
                        }
                    ],
                    "_id": "62ff74bfe80b11ade2d34455"
                }
            ]
        },
        {
            "name": "doing",
            "_id": "62fa5aa25778ec97bc6ee234",
            "tasks": []
        },
        {
            "name": "done",
            "_id": "62fa5aa25778ec97bc6ee235",
            "tasks": []
        }
    ],
    "__v": 0
}
// @desc    Edit task
// @route   PUT /api/tasks/:id
// @access  Private
const editTask = asyncHandler(async (req, res) => {
  const { title, description, subtasks, status } = req.body;

  const task = await Board.findOne({ "columns.tasks._id": req.params.id });

  const taskStatus = await Board.findOne({
    "columns.tasks._id": req.params.id,
    "columns._id": status,
  });

  if (!task) {
    res.status(400);
    throw new Error("Task not found");
  }

  // Check for user
  if (!req.user) {
    res.status(401);
    throw new Error("User not found");
  }

  // Make sure the logged in user matches the task user
  if (task.user.toString() !== req.user.id) {
    res.status(401);
    throw new Error("User not authorized");
  }

  if (taskStatus) {
    const updatedTask = await Board.findOneAndUpdate({
      "columns.tasks._id": req.params.id,
    });
  }


  task.columns.map(async (val) => {
    // check if tasks id equals the status id in the request body
    if (val._id.toString() === status) {
      const updatedTask = await Board.findOneAndUpdate(
        {
          "columns.tasks._id": req.params.id,
        },
        { $set: { "columns.$[].tasks": { _id: req.params.id } } },
        { new: true }
      );
    }
  });
});

我最近不得不做類似的事情,但我找不到使用 mongoose 更新它的方法。 所以我想出了一個解決方法。

完成所有檢查后

// retrieve the column index you want to update (I assume you have only these 3 columns)
const columnIndex = _.findIndex(task.columns, { name: "todo" });

// retrieve the actual column object
const column = task.columns[columnIndex ];

// get the index of the specific task you want to update
const taskIndex = _.findIndex(column.tasks, { _id: req.params.id });

// manipulate whatever you want here on the specific task by its index
task.columns[columnIndex].tasks[taskIndex]._id = req.params.id

// then finally you need to update the whole columns array
await Board.updateOne({your query here}, {
  $set: {
    columns: task.columns
  }
});

這實際上很臟,但是您的數據的結構非常困難。

我在示例中使用了lodash 你可以自由使用 JavaScript 的數組方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM