2017-06-03 129 views
0

我的数据如下:Model.update不工作的猫鼬

{ 
"profileID": "123", 
"fullname": "Name", 
"notifications": [ 
    { 
    "read": false, 
    "date": "2017-05-06 13:40:01", 
    "post": "5555555", 
    "action": "commented", 
    "profileID": "456" 
    }, 
    { 
    "read": false, 
    "date": "2017-05-06 13:40:15", 
    "post": "5555555", 
    "action": "commented", 
    "profileID": "456" 
    } 
]} 

我试图做一个节点API路线能够更新每个通知。对于唯一性,可以使用日期变量。

所以总结:

  • 查找用户简档
  • 得到他/她的通知
  • 更新值相匹配的日期通知。

我构建它以下列方式:

apiRouter.post('/api/changeNotificationStatus', function(req, res){ 

     userModel.update(
      {profileID: req.body. profileID, "notifications.date": req.body.date, "notifications.post": req.body.post, "notifications.action": req.body.action}, 
      {$set:{"notifications.$.read": true}}, 
      {multi: false}, 

      function(err, data) { 
       if (err){ 
        console.log(err); 
       } else { 
        console.log(data); 
       } 
      }); 

    }); 

不会有任何错误,但我得到以下几点:

{ n: 0, nModified: 0, ok: 1 } 

我已确认这两个变量:REQ。 body.profileID,req.body.date,req.body.date,req.body.post和req.body.action都可以通过。

我做错了什么?

PS:谢谢尼尔Lunn指着我model.update文章!

+0

@ neil-lunn - 我已经更新了问题,所以它不再是重复的。 –

+0

仍然是重复的。你的语法错了。再次阅读答案。这是更正。 '{profileID:req.body.profileID,“notifications.date”:req.body.date,“notifications.post”:req.body.post,“notifications.action”:req.body.action}'。所以你不要在更新的“查询”部分使用'$'。你只能在'$ set'之后的部分使用它。 –

+0

感谢您指出并为这些愚蠢的错误感到遗憾。但是,我只是试了一下,得到了相同的结果,即:{n:0,nModified:0,ok:1} ...我再次检查了参数(通过调试器),它们似乎很好。有任何想法吗? –

回答

0

只是帮人谁碰到这个来的时候,出现了许多问题:

1)的usermodel的模式是错误的,如,它应该是:

notifications: [{ 
    read: Boolean, 
    date: Date, 
    post: String, 
    action: String, 
    profileID: String 
}] 

相反的:

notifications: [{ }] 

2)在userModel.update命令,我应该已经做了:

new Date(req.body.date) 

相反的:

req.body.date 

希望这可以帮助别人的未来。