我知道有成百上千个相同的问题,但是我已经阅读了,无法解决。
我想做的是在具有给定req.body
参数的任务数组中更新给定的对象
我尝试了大多数解决方案,但可能错误地实施了它们。这与我能想象的最接近。
{
"_id" : ObjectId("5f421bf98bc1d33d7c646535"),
"todoSections" : [
{
"_id" : ObjectId("5f42202b9c6c3040ea0d5326"),
"name" : "first section",
"tasks" : [
{
"status" : 4,
"priority" : 2,
"_id" : ObjectId("5f42274952e6864b19252e37"),
"name" : "task 1",
"assignedUsers" : [],
"comments" : [],
"subTasks" : []
},
{
"status" : 4,
"priority" : 2,
"_id" : ObjectId("5f422a6377eaa74f2e403940"),
"name" : "task 2",
"creationDate" : ISODate("2020-08-23T08:35:47.497Z"),
"assignedUsers" : [],
"comments" : [],
"subTasks" : []
}
]
},
{
"_id" : ObjectId("5f42202f9c6c3040ea0d5327"),
"name" : "another section..",
"tasks" : []
},
],
"__v" : 0
}
const mongodb = require("mongodb");
const { ObjectId } = require("mongodb");
Todo.updateOne(
{
_id: req.body.todoId,
},
{
$set: {
"todoSections.$[outer].tasks$[inner]": {
name: req.body.name,
status: req.body.status
},
},
},
{
arrayFilters: [
{ "outer._id": ObjectId(req.body.sectionId) },
{ "inner._id": ObjectId(req.body.taskId) },
],
},
(err, result) => {
if (!err) {
if (result.nModified === 0) {
res.status(400).send(result);
console.log(result);
return;
} else {
res.status(200).send("ok");
}
} else {
res.status(400).send(err);
console.log(err);
return;
}
}
);
{
"ok": 0,
"n": 0,
"nModified": 0
}