[
{
_id: "...",
title: "some title",
tasks: [
{
id: "...",
field1: "abc",
field2: "def"
},
...
]
},
...
]
I would like to modify both field1 and field2 for a given task. I see lots of examples of how to update a single field, but not multiple fields.
I've tried the following, but it's simply replacing the whole task object with only the fields I'm setting.
let changes = { field1: "123", field2: "456" };
db.collection("lists")
.updateOne(
{
"_id": new ObjectId(req.params.listId),
"tasks.id": req.params.id
},
{ $set: { "tasks.$": changes } }
);
Appreciate any help. Thanks.
WORKING SOLUTION
let changes = { field1: "123", field2: "456" };
Object.keys(changes).forEach(key => {
changes[`tasks.$.${key}`] = changes[key];
delete changes[key];
});
db.collection("lists")
.updateOne(
{
"_id": new ObjectId(req.params.listId),
"tasks.id": req.params.id
},
{ $set: changes }
);