简体   繁体   中英

Error while updating a particular object in an array with Mongoose

I need to update a particular object inside an array

{
    "_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
        }
    ]
}

I tried a lot , I don't know what I am missing.

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

I am getting an error response

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')"
}

I also tried

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

                    }
                })

same error.

Please help me in figuring out what I am missing,

I tried even this

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

Nothing works. Please help me to figure out the issue

Thanks, Balu

Using the update() mongoose method means you are updating all your fields including your _id field which is immutable in Mongo. This results in throwing that error.

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

So instead initialize your Event model and change the attributes and use the save() method instead.

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

You may try passing the id field in values to updated, as if you see the console by passing the value to be updated, it has the new _id filed attached. so try in following way:

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

this is not a big issue , It causes due to save new object for modal. Just save your object in some var.

Ex :-

router.put('/brand/:id', function (req, res) {
    var brand = {
        Name: req.body.Name,
        Description: req.body.Description,
        Date_Modify: moment()
    };
            Brand.findByIdAndUpdate(req.params.id, brand, {
                new: true
            }, function (error, doc) {
                if (error) {
                    if (error.code == 11000) {
                        res.json({
                            success: false,
                            message: 'Update Failed ,Brand Name Already Exist.'
                        });
                    } else {
                        res.json({
                            success: false,
                            message: error
                        });
                    }
                } else if (doc) {
                    res.json({
                        success: true,
                        status: res.statusCode,
                        message: 'Brand Updated Successfully.',
                        data: doc
                    });
                } else {
                    res.json({
                        success: false,
                        status: 404,
                        message: 'Brand Not Found.',
                        data: doc
                    });
                }
            });
        });

You can go through it and solve your issue.

Actually while making object it create a new object (_id) so it can't save new id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM