majid jiji
majid jiji

Reputation: 414

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})?

Upvotes: 18

Views: 11060

Answers (1)

dnickless
dnickless

Reputation: 10918

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.

Upvotes: 22

Related Questions