Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between findByIdAndUpdate() and findOneAndUpdate(), in mongoose?

Can anybody explain the difference between findByIdAndUpdate() and findOneAndUpdate() in mongoose.

And also the difference between findOneAndUpdate(req.params.id) and findOneAndUpdate({_id: req.params.id})?

like image 931
majid jiji Avatar asked Nov 12 '17 21:11

majid jiji


People also ask

What is difference between update and findOneAndUpdate?

The . findOneAndUpdate method issues a mongodb . findAndModify update command and returns the found document (if any) to the callback or return the modified document rather than the original if the new option is true and the . update execute the query as an update() operation.

What does findByIdAndUpdate return in mongoose?

Mongoose | findByIdAndUpdate() Function The findByIdAndUpdate() function is used to find a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback.

What does findOneAndUpdate return mongoose?

By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied.

Is findOneAndUpdate Atomic?

According to these docs , single write transactions are atomic. So with findOneAndUpdate, this would indeed be atomic.


1 Answers

Check out the documentation for findByIdAndUpdate() and findOneAndUpdate() which clearly states:

findByIdAndUpdate(id, ...) is equivalent to findOneAndUpdate({ _id: id }, ...).

So, really, findByIdAndUpdate() is just a convenient shorthand version for an update scenario that is likely to happen very often ("update by id").

With respect to your second question:

And also the difference between findOneAndUpdate(req.params.id) and findOneAndUpdate({_id: req.params.id})?

The first one will simply crash as the first parameter to findOneAndUpdate() is expected to be a filter document. The second one will work and is equivalent to findByIdAndUpdate(req.params.id) as already noted above.

like image 172
dnickless Avatar answered Nov 16 '22 02:11

dnickless