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})?
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.
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.
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.
According to these docs , single write transactions are atomic. So with findOneAndUpdate, this would indeed be atomic.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With