How do I remove documents using Node.js Mongoose? How do I remove documents using Node.js Mongoose? express express

How do I remove documents using Node.js Mongoose?


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.


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.


docs is an array of documents. so it doesn't have a mongooseModel.remove() method.

You can iterate and remove each document in the array separately.

Or - since it looks like you are finding the documents by a (probably) unique id - use findOne instead of find.