簡體   English   中英

為什么我的Mongoose查詢沒有更新MongoDB數據庫中嵌套數組中的值?

[英]Why is my Mongoose query not updating a value in a nested array in the MongoDB databse?

我試圖以幾種方式實現此目的,但似乎都沒有效果。 我需要做的就是將特定Notifications對象(由其_id找到)的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的類型嗎? 如果是這樣,請嘗試將req.body.NotificationId為ObjectId。 將查詢更改為

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

嘗試使用“ $ set”而不是$ set。 確保您輸入的ID正確無誤。 Update回調帶有更新的文檔-打印出來以了解會發生什么。

$只引用數組中的第一項。 如果要更新所有內容,則必須使用查找並保存:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM