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?


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.

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

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.

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:

remove() has been deprecated. Use deleteOne(), deleteMany() or bulkWrite().

The code I use

TeleBot.deleteMany({chatID: chatID}, function (err, _) {
                if (err) {
                    return console.log(err);
                }
            });