简体   繁体   中英

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?

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)}

Try '$set' instead of $set. Ensure that you are getting id coming in correctly. Update callback comes with updated document - print that to know what happens.

The $ is referring only the first item in the array. If you want to update all you have to use find and save:

UserProfile.findOne({
        'Notifications._id' : req.body.NotificationID
    }, function(err, doc) {
         _.find(doc.Notifications, {_id: req.body.NotificationID}).Status = 1;

         doc.save(function (err) {
        if (err)
            res.send(err);
    })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM