I use mongoose in node js and I want to make a boolean toggle, But when I use findOneAndUpdate(As I wrote) I get "done" as false but the second time "done" is not true
finally, I want to get such logic: when I click the button, "done" should become false if it is true and the same, when it is false it should become true
{
"_id": "63be594eaceb91f14825b144",
"tasksTitle": "Daily",
"collectioner": "63bc41041e463e09c07db3fe",
"collectionAuthor": "63b31ee65e03accdf60ca705",
"tasksItems": [
{
"taskItemTitle": "exampleTitle",
"deadline": 0,
"done": true,
"_id": "63be49f56c9c394d282b155f"
}
]
}
argument "taskItemId: 63be49f56c9c394d282b155f"
tasksModel.findOneAndUpdate(
{
"tasksItems._id": taskItemId,
tasksItems: {
$elemMatch: {
_id: taskItemId,
},
},
},
[{ $set: { tasksItems: { done: { $eq: [false, "$done"] } } } }],
{ new: true }
);
CodePudding user response:
The easiest solution might be to retrieve the task and update the taskItems
independently:
const task = await tasksModel.findOne({ 'tasksItems._id': taskItemId });
if (!task) return;
for (let i = 0; i < task.tasksItems.length; i ) {
task.tasksItems[i].done = !task.tasksItems[i].done;
}
await task.save();