为什么我的Mongoose查询不更新MongoDB数据库中的嵌套数组中的值?

我试图用几种方式来实现这一点,而且似乎没有任何工作。 我需要做的只是将特定Notifications对象(由其_idfind)的Status值从0更改为1

示例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" } ] ..... } 

我的路线:

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

我没有得到任何错误,更新似乎没有发生。 问题是什么?

Notifications._id ObjectId的types? 如果是这样,请尝试将req.body.NotificationId为ObjectId。 将查询更改为

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

尝试'$ set'而不是$ set。 确保你得到正确的身份证。 更新callback来与更新的文件 – 打印,知道会发生什么。

$是只引用数组中的第一个项目。 如果你想更新所有你必须使用查找和保存:

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