I am not able to differentiate findOneAndDelete() And findOneAndRemove() in the mongoose documentaion.
Query.prototype.findOneAndDelete()
This function differs slightly from Model.findOneAndRemove() in that findOneAndRemove() becomes a MongoDB findAndModify() command, as opposed to a findOneAndDelete() command. For most mongoose use cases, this distinction is purely pedantic. You should use findOneAndDelete() unless you have a good reason not to.
Returns the deleted document.
Mongoose | findOneAndDelete() Function The findOneAndDelete() function is used to find a matching document, remove it, and passes the found document (if any) to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.
The findByIdAndDelete() is a function in Mongoose used to find a document by the _id field and then remove the document from the collection. It returns the document removed or deleted.
TLDR: You should use findOneAndDelete() unless you have a good reason not to.
Longer answer:
From the Mongoose documentation of findOneAndDelete:
This function differs slightly from Model.findOneAndRemove() in that findOneAndRemove() becomes a MongoDB findAndModify() command, as opposed to a findOneAndDelete() command. For most mongoose use cases, this distinction is purely pedantic. You should use findOneAndDelete() unless you have a good reason not to.
Mongoose Docs findOneAndDelete
In MongoDB native client (Mongoose is different) passing { remove: true }
to findAndModify
makes it remove the found document, it's behavior in this case would appear quite similar to findOneAndDelete
. However, there are some differences when using other options:
query
, sort
, doc
(the update object), options
and a callback
. findOneAndDelete only takes 3 (filter
or query, options
and a callback
)options
for findAndModify
include w
, wtimeout
and j
for write concerns, as:
“the level of acknowledgment requested from MongoDB for write operations to a standalone mongod or to replica sets or to sharded clusters.“ or simply guarantee levels available for reporting the success of a write operation.
options
for findOneAndDelete
do not include write concerns configuration.
findAndModify
lets you return the new document and remove it at the same time.
Example:
// Simple findAndModify command returning the new document and // removing it at the same time collection.findAndModify({b:1}, [['b', 1]], {$set:{deleted: Date()}}, {remove:true}, calback)
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