[英]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.