Thursday, 22 January 2015

How to use findByIdAndUpdate on mongdb2.4

backbone client update a model property:
ocase.save({ currentStep : theStep },callback);
server side mongoose code :
OCase.findByIdAndUpdate(req.params.id,
        req.body, callback);
it works fine on mongodb2.6, but it doesn't work on mongodb2.4, and the error is :
update err:MongoError: exception: Mod on _id not allowed
so I tried to remove "_id",and only save other attributes:
OCase.findByIdAndUpdate(req.params.id,
            {subject    : req.body.subject,
            description : req.body.description    
        },callback);
then I got another error :
update err:TypeError: Cannot read property '_id' of undefined
I am really confused, what can I do now?
Finally, I have to query(findById) the document first, and then call "save" method to update.
OCase.findById(req.params.id,
        function(err,ocase){
            ocase.set(req.body);
            ocase.save(function(err,ocase){
                res.send(ocase);

            });
        });

1 comment:

  1. Solve it by adding $set operator:
    OCase.findByIdAndUpdate(req.params.id,
    {$set:{subject : req.body.subject,
    description : req.body.description,
    currentStep: req.body.currentStep
    }},callback);

    ReplyDelete