javascript - 使用 Mongoose 更新数组中的特定对象时出错

标签 javascript node.js mongodb mongoose

我需要更新数组中的特定对象

{
    "_id": "543e2f8e769ac100008777d0",
    "createdDate": "2014-10-15 01:25 am",
    "cancle": false,
    "eventDateAndTime": "2014-02-12 12:55 am",
    "eventstatus": true,
    "userPhone": "44444444",
    "userId": "54334def7e85de48638d1069",
    "createdBy": "four",
    "eventName": "real tea",
    "__v": 0,
    "friends": [
        {
            "phoneNumber": "11111111",
            "userName": "one",
            "userId": "54310801e2659ecc3650100b",
            "status": 0
        },
        {
            "phoneNumber": "22222222",
            "userName": "two",
            "userId": "54310814e2659ecc3650100c",
            "status": 1
        }
    ]
}

我试了很多,我不知道我错过了什么。

event.update(
                    function(err, eventSaved) {
                    if(err) {
                 res.json({'err':err});
                    }
                })

我收到错误响应

err: {
    name: "MongoError"
    code: 66
    err: "After applying the update to the document {_id: ObjectId('543e2ecb74d70100001545ad') , ...}, the (immutable) field '_id' was found to have been altered to _id: ObjectId('543e2f8e769ac100008777d0')"
}

我也试过

event.update({'friends.userId': req.param.friendId}, {'$set': {
                    'friends.$.status': status }},
                    function(err, eventSaved, eve) {
                    if(err) {

                    }
                })

同样的错误。

请帮我弄清楚我错过了什么,

这个我也试过

Events.findOneAndUpdate({_id: req.params.eventId}, {$set: {'friends[keyValue].status': 7 }}, {upsert: true, "new": false}).exec(function(err, thing) {
                    console.dir(thing);
                });

没有任何作用。请帮我找出问题

谢谢, 巴鲁

最佳答案

使用 update() mongoose 方法意味着您正在更新所有字段,包括在 Mongo 中不可变的 _id 字段。这会导致抛出该错误。

event.update(function(err, eventSaved) {
                    if(err) {
                 res.json({'err':err});
                    }
                })

因此,请改为初始化您的事件模型并更改属性,然后改用 save() 方法。

event.save(function(err, eventSaved){
 //some code here
})

关于javascript - 使用 Mongoose 更新数组中的特定对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26420403/

相关文章:

javascript - Passport 身份验证回调而不是重定向

php - 从mysql背景理解mongodb结构

node.js - 将 MongoDB 与 Node.js 一起使用的最佳方式?

c# - DDD解决方案结构

javascript - Extjs GridPanel 验证

javascript - 无法附加 html 元素 jquery

node.js - Nodejs 导出函数

这种格式的 JavaScript 日期 : "Wednesday, March 03, 2010 05:44:15 PM"

javascript - 在循环中设置输入文本的焦点

javascript - Sencha ExtJS 4.2 : how can I synchronize two combo editors in a grid?