I have the following MongoDB document and I'm trying to update the selected answer object in a nested array.
{
"days":[
{
"data":{
"average_score":{
"$numberDecimal":"80"
},
"metabolic_score":{
"$numberDecimal":"80"
},
"cardio_score":{
"$numberDecimal":"80"
},
"glucose_levels":[
{
"_id":{
"$oid":"5fdf461407a0a61cb7593bdb"
},
"start_date":"eee",
"end_date":"eee",
"value":{
"$numberDecimal":"80"
}
}
],
"heart_rates":[
],
"summaries":[
{
"actions":[
],
"_id":{
"$oid":"5fdf5a8182bb38276953c3dc"
},
"questions":[
]
},
{
"actions":[
],
"_id":{
"$oid":"5fdf5b71cac79b28cc840e2b"
},
"questions":[
{
"answers":[
"gugu",
"guru?"
],
"_id":{
"$oid":"5fdf5b71cac79b28cc840e2d"
},
"text":"xxxx",
"selected_answer":"gugu!"
}
]
}
],
"moods":[
{
"_id":{
"$oid":"5fdf478ceec5901d4614188a"
},
"labels":[
]
},
{
"_id":{
"$oid":"5fdf4c3affa900202d89fa7a"
},
"labels":[
]
}
]
},
"_id":{
"$oid":"5fdf461407a0a61cb7593bdc"
},
"day":"18-12-2020"
}
]
}
Currently, the code that I'm using is following:
User.findOneAndUpdate(
{ _id: getUserId(req), "days.day": req.body.day},
{ $push: {"days.$.data.summaries.$[summ].questions.$[quest].selected_answer": req.body.selected_answer}},
{ arrayFilters: [{"summ._id": ObjectID("5fdf5b71cac79b28cc840e2d")}, {"quest._id": ObjectID("5fdf5b71cac79b28cc840e2d")}]},
(err, user) => {
if (err) {
res.status(500).send({data: { message: err }});
return;
}
else if (user) {
res.status(200).send({data: { message: "updated!"}})
}
}
)
After the request gets executed it says "updated!" but the selected_answer entry is not actually updated. What am I missing? Somehow, it doesn't find the proper path.
The correct way of updating an existing entry is:
User.findOneAndUpdate(
{ _id: getUserId(req), "days.day": req.body.day},
{ $set: {"days.$.data.summaries.$[summ].questions.$[quest].selected_answer": req.body.selected_answer}},
{ arrayFilters: [{"summ._id": ObjectID("5fdf5b71cac79b28cc840e2d")}, {"quest._id": ObjectID("5fdf5b71cac79b28cc840e2d")}]},
(err, user) => {
if (err) {
res.status(500).send({data: { message: err }});
return;
}
else if (user) {
res.status(200).send({data: { message: "updated!"}})
}
}
)