Mongoose: findByIdAndUpdate does not return updated array with $push

Created on 28 Apr 2015  路  2Comments  路  Source: Automattic/mongoose

I experienced a weird issue with Mongoose 4.0.2 and MongoDB 3.0.2
When I $push a value to an array, the value has been added to the array in the database but findByIdAndUpdate return the old array (not updated).

User.findByIdAndUpdate(req.user._id, {
  $push: { friends: friend._id }
}, cb);

I was forced to tricky hack like:

User.findByIdAndUpdate(req.user._id, {
  $push: { friends: friend._id }
}, function (err, user) {
  user.friends.push(friend._id);
  cb(err, user);
});

Thanks :)

Most helpful comment

See release notes section on #2262. The following code will get you the behavior you want.

User.findByIdAndUpdate(req.user._id, {
  $push: { friends: friend._id }
}, { 'new': true}, cb);

All 2 comments

See release notes section on #2262. The following code will get you the behavior you want.

User.findByIdAndUpdate(req.user._id, {
  $push: { friends: friend._id }
}, { 'new': true}, cb);

@vkarpov15 Thanks :+1:

Was this page helpful?
0 / 5 - 0 ratings