Reputation: 805
I'm new in MongoDB an I'm using mongoose with nodejs. Currently I'm trying to update a nested Array which looks like this:
array1: [
{
name: "one"
array2: [
{
value1: "test",
value2: "test2"
}
]
}
]
So now I want to update the value1 in array2. How can I achieve this? I'm using the atomic operator two times in my code like this but it doens't work:
const data = await DB.findOneAndUpdate(
{
"array1.name": "one",
"array1.array2.value1": "test"
},
{
"$set": {
"array1.$.array2.$.value1": "test changed"
},
}
);
Any ideas how I can do this? Thanks! :)
Upvotes: 0
Views: 61
Reputation: 2011
You can use arrayFilters to update the nested array.
const data = await DB.findOneAndUpdate(
{},
{
$set: {
"array1.$[elem1].array2.$[elem2].value1": "test changed",
},
},
{
arrayFilters: [{ "elem1.name": "one"}, {"elem2.value1": "test"}],
}
);
Upvotes: 1