2017-06-03 83 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 

希望這可以幫助別人的未來。