繁体   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