2016-07-14 40 views
1

我试图用几种方式来实现这一点,而且都没有效果。 我需要做的是将特定Notifications对象(由其_id找到)的Status值从0更改为1为什么我的Mongoose查询不更新MongoDB数据库中嵌套数组中的值?

例JSON:

{ 
    "_id": "577fbf0c7c6e88600ede5e73", 
    "updatedAt": "2016-07-14T11:27:18.670Z", 
    "createdAt": "2016-07-08T14:56:12.013Z", 
    "Name": "Name", 
    "Email": "[email protected]", 
    "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); 
    }) 
}); 

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

回答

2

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

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

是的,这工作!非常感谢你。你有解释这个参考链接吗?我是新来的,所以我想看看它 – Poot87

+0

你仍然会始终更新第一个通知 –

+0

@ Poot87好!在mongodb和mongoose中,“ObjectId”类型与“String”类型不同。你可以在[http://mongoosejs.com/docs/api.html#schema_Schema.Types](http://mongoosejs.com/docs/api.html#schema_Schema.Types)检查猫鼬的类型。 – wikrsh

0

尝试'$ set'而不是$ set。 确保你得到正确的身份证。 更新回调附带更新的文档 - 打印知道发生了什么。

+0

您的意思是? '{ok:1,nModified:0,n:0}' – Poot87

+0

在设置后添加{'$ new':true}作为参数 - 检查更新的文档 – npr

0

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

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

它只是用来更新一个由它的_id属性引用的特定通知对象。 – Poot87

+0

好的,但它不会工作,因为你工作在整个文档。我会修复我的答案 –

+0

谢谢你的回答。它抛出这个错误:'ReferenceError:_没有定义' – Poot87