Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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 updatedObj by 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.

2 Answers

0 votes
by (106k points)

You should use the below-mentioned code:-

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

0 votes
by (108k points)

In Mongoose 4.0, the by default value for the new choice of findByIdAndUpdate (and findOneAndUpdate) has changed to false. You have 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) {...

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...