Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove documents using Node.js Mongoose?

FBFriendModel.find({     id: 333 }, function (err, docs) {     docs.remove(); //Remove all the documents that match! }); 

The above doesn't seem to work. The records are still there.

Can someone fix?

like image 267
TIMEX Avatar asked Apr 27 '11 19:04

TIMEX


People also ask

How do you delete an item from MongoDB using Mongoose?

remove() is deprecated and you can use deleteOne(), deleteMany(), or bulkWrite() instead. As of "mongoose": ">=2.7. 1" you can remove the document directly with the . remove() method rather than finding the document and then removing it which seems to me more efficient and easy to maintain.

How do I delete a file in MongoDB node JS?

To delete a record, or document as it is called in MongoDB, we use the deleteOne() method. The first parameter of the deleteOne() method is a query object defining which document to delete. Note: If the query finds more than one document, only the first occurrence is deleted.

How do you use Find one and delete in Mongoose?

Mongoose | findOneAndDelete() FunctionThe 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.


2 Answers

If you don't feel like iterating, try

FBFriendModel.find({ id:333 }).remove( callback ); 

or

FBFriendModel.find({ id:333 }).remove().exec(); 

mongoose.model.find returns a Query, which has a remove function.

Update for Mongoose v5.5.3 - remove() is now deprecated. Use deleteOne(), deleteMany() or findOneAndDelete() instead.

like image 102
Yusuf X Avatar answered Oct 13 '22 13:10

Yusuf X


UPDATE: Mongoose version (5.5.3)

remove() is deprecated and you can use deleteOne(), deleteMany(), or bulkWrite() instead.

As of "mongoose": ">=2.7.1" you can remove the document directly with the .remove() method rather than finding the document and then removing it which seems to me more efficient and easy to maintain.

See example:

Model.remove({ _id: req.body.id }, function(err) {     if (!err) {             message.type = 'notification!';     }     else {             message.type = 'error';     } }); 

UPDATE:

As of mongoose 3.8.1, there are several methods that lets you remove directly a document, say:

  • remove
  • findByIdAndRemove
  • findOneAndRemove

Refer to mongoose API docs for further information.

like image 26
Diosney Avatar answered Oct 13 '22 13:10

Diosney