How do I remove documents using Node.js Mongoose?

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?

Solutions/Answers:

Solution 1:

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.

Solution 2:

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.

Related:  Method to show native datepicker in Chrome

Solution 3:

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.

Solution 4:

This for me is the best as of version 3.8.1:

MyModel.findOneAndRemove({field: 'newValue'}, function(err){...});

And it requires only one DB call.
Use this given that you don’t perform any remove actions pior to the search and removal.

Solution 5:

Simply do

FBFriendModel.remove().exec();

Solution 6:

mongoose.model.find() returns a Query Object which also has a remove() function.

You can use mongoose.model.findOne() as well, if you want to remove only one unique document.

Else you can follow traditional approach as well where you first retrieving the document and then remove.

yourModelObj.findById(id, function (err, doc) {
    if (err) {
        // handle error
    }

    doc.remove(callback); //Removes the document
})

Following are the ways on model object you can do any of the following to remove document(s):

yourModelObj.findOneAndRemove(conditions, options, callback)

yourModelObj.findByIdAndRemove(id, options, callback)

yourModelObj.remove(conditions, callback);

var query = Comment.remove({ _id: id });
query.exec();