Poot87 Poot87 - 4 months ago 19
Node.js Question

Why is my Mongoose query not updating a value in a nested array in the MongoDB databse?

I have tried to implement this in several ways and none seem to work.
All I need to do is change the

Status
value of a specific
Notifications
object (found by its
_id
) from
0
to
1
.

Example JSON:

{
"_id": "577fbf0c7c6e88600ede5e73",
"updatedAt": "2016-07-14T11:27:18.670Z",
"createdAt": "2016-07-08T14:56:12.013Z",
"Name": "Name",
"Email": "test@test.com",
"Notifications": [
{
"_id": "5787644108edec801e9cd0ab",
"Title": "They commented on This",
"Type": 1,
"Status": 0,
"TeamID": "578357109bb105602b1cba27",
"DraftID": "578357b89bb105602b1cba2a"
},
{
"_id": "578777167d1f3424251c361f",
"Title": "He commented on That",
"Type": 1,
"Status": 0,
"TeamID": "578357109bb105602b1cba27",
"DraftID": "578357b89bb105602b1cba2a"
}
]
.....
}


My route:

router.post('/notification', function (req, res) {
UserProfile.update({
'Notifications._id' : req.body.NotificationID
}, {
'$set' : {
'Notifications.$.Status' : 1
}
}, function (err) {
if (err)
res.send(err);
})
});


I don't get any errors and the update doesn't seem to happen.
What could the problem be?

Answer

Is the type of Notifications._id ObjectId? If so, try cast req.body.NotificationId to ObjectId. Change the query to

{'Notifications._id' : mongoose.Types.ObjectId(req.body.NotificationID)}
Comments