Search code examples
mongodbbackbone.jsmongoosemongodb-query

How to use findByIdAndUpdate on mongodb2.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);

            });
        });

Solution

  • Solve it by adding the $set operator:

    OCase.findByIdAndUpdate(req.params.id, {
            $set: {
                subject: req.body.subject,
                description: req.body.description,
                currentStep: req.body.currentStep
            }
        }, callback);