Mongoose findByIdAndUpdate not returning correct model

node.jsMongodbMongoose

node.js Problem Overview


I have an issue I've not seen before with the Mongoose findByIdAndUpdate not returning the correct model in the callback.

Here's the code:

    var id = args._id;
    var updateObj = {updatedDate: Date.now()};
    _.extend(updateObj, args);

    Model.findByIdAndUpdate(id, updateObj, function(err, model) {
        if (err) {
            logger.error(modelString +':edit' + modelString +' - ' + err.message);
            self.emit('item:failure', 'Failed to edit ' + modelString);
            return;
        }
        self.emit('item:success', model);
    });

The original document in the db looks like this:

{
    _id: 1234
    descriptors: Array[2],
    name: 'Test Name 1'
}

The updateObj going in looks like this:

{
    _id: 1234
    descriptors: Array[2],
    name: 'Test Name 2'
}  

The model returned from the callback is identical to the original model, not the updatedObj. If I query the db, it has been updated correctly. It's just not being returned from the database.

This feels like a 'stupid-user' error, but I can't see it. Any ideas greatly appreciated.

node.js Solutions


Solution 1 - node.js

In Mongoose 4.0, the default value for the new option of findByIdAndUpdate (and findOneAndUpdate) has changed to false, which means returning the old doc (see #2262 of the release notes). So you need to explicitly set the option to true to get the new version of the doc, after the update is applied:

Model.findByIdAndUpdate(id, updateObj, {new: true}, function(err, model) {...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonRedView Question on Stackoverflow
Solution 1 - node.jsJohnnyHKView Answer on Stackoverflow