5

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

4
  • from the error, it seems that you are trying to change the _id Commented Oct 17, 2014 at 7:54
  • No, i am not chaning the id. Commented Oct 17, 2014 at 7:55
  • Your query works fine for me Commented Oct 17, 2014 at 8:16
  • Which one. can you please let me know. Commented Oct 17, 2014 at 8:20

3 Answers 3

1

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
})
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.