I'm trying to update some of the value inside nested arrays using id
as shown below:-
Nested array:-
let people = [
{
"_id": 1,
"name": "Person 1",
"pets": [
{
"_id": 1,
"name": "Tom",
"category": "cat",
"favFood": [
{
"_id": 1,
"name": "steamed fish", // this will be updated
"gred": "A" // this will be updated
},
{
"_id": 2,
"name": "fried fish",
"gred": "B"
}
]
},
{
"_id": 2,
"name": "Jerry",
"category": "mouse",
"favFood": [
{
"_id": 1,
"name": "cheese",
"gred": "C"
}
]
}
]
}
]
Right now I've something like this:-
People.updateOne(
{ "$set": { "pets.$[petID].favFood.$[favFoodID].name" : "bbq fish",
"pets.$[petID].favFood.$[favFoodID].gred" : "A+" }
},
{
multi: true,
arrayFilters: [
{ "petID._id": 1 }, // pet with id of '1'
{ "favFoodID._id": 1 } // favFood with id of '1'
]
},
(err, success) => {
if(err) res.json({ message: `Unsuccessful!`, report: err })
else res.json({ message: `Successful!`, report: success })
}
)
But, unfortunately I got error of "message": "\"_id\" is not allowed"
. And I don't know which _id
that was not allowed or cause of the error.
What I would want is to alter or update as following:-
let people = [
{
"_id": 1,
"name": "Person 1",
"pets": [
{
"_id": 1,
"name": "Tom",
"category": "cat",
"favFood": [
{
"_id": 1,
"name": "bbq fish", // this value was updated
"gred": "A+" // this value was updated
},
{
"_id": 2,
"name": "fried fish",
"gred": "B"
}
]
},
{
"_id": 2,
"name": "Jerry",
"category": "mouse",
"favFood": [
{
"_id": 1,
"name": "cheese",
"gred": "C"
}
]
}
]
}
]
Can anyone direct me on which part on my codes above causing the error?
Adjusted updateOne
:-
People.updateOne(
{ "_id": 1,
"pets._id": 1,
"favFood._id": 1
},
{ $set: { "pets.favFood.$$.name" : "bbq fish",
"pets.favFood.$$.gred" : "A+", }
},
(err, success) => {
if(err) res.json({ message: `Unsuccessful!`, report: err })
else res.json({ message: `Successful!`, report: success })
}
)
It's able to return Successful!
. But the values in database does not change. From here, how can I tweak my code?