Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between findByIdAndRemove and findByIdAndDelete in mongoose?

Tags:

mongoose

The documentation here doesn't provide much of an explanation for why there are two different operations to accomplish the same thing, so I'm wondering what the differences are between them. Why might I choose to use one over the other?

like image 934
Katie Avatar asked Jan 07 '19 20:01

Katie


People also ask

What is findByIdAndDelete?

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.

What is the difference between findOneAndRemove and findOneAndDelete?

Both of them are almost similar except findOneAndRemove uses findAndModify with remove flag and time complexity will be a bit higher compare to findOneAndDelete because you are doing an update. Delete are always faster. Both functions send the exact same command over the wire to MongoDB.

How do you use findOneAndDelete?

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.


1 Answers

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.

the offical site https://mongoosejs.com/docs/api.html#model_Model.findOneAndDelete

like image 104
冉娃娃 Avatar answered Sep 23 '22 11:09

冉娃娃