Mongoose Model.remove(callback) doesn't remove anything from my collection

I’m trying to remove all content from my Mongoose database but nothing seems to work.

I have tried

# CoffeeScript
MyModel.find().remove((err) -> console.log('purge callback'))

# JavaScript
MyModel.find().remove(function() { console.log('purge callback') })

And

# CoffeeScript
MyModel.find().remove({}, (err) -> console.log('purge callback'))

# JavaScript
MyModel.find().remove({}, function() { console.log('purge callback') })

Even removing the .find() step or adding a .exec() my callback never shows and my data are still here.

I am pretty sure that my model and connection are ok:

  • I can see the connections in Mongo’s log
  • I can add documents by manipulating the same model elsewhere

Related: How do I remove documents using Node.js Mongoose?

EDIT

My problem was caused by a syntax mistake that wasn’t displayed. The selected answer does work and so does the above code. Moderators are welcome to remove my question if it seems necessary.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

It’s not a “query” object as returned by Mongoose, the only valid method here is .remove():

MyModel.remove(function(err,removed) {

   // where removed is the count of removed documents
});

Which is the same as:

MyModel.remove({}, function(err,removed) {

});

Also, how are you determining no documents are removed? Possibly looking in the wrong collection. Mongoose pluralizes the collection name by default unless you explicitly specify the collection name as in:

mongoose.Model( "MyModel", myModelSchema, "mymodel" )

Without that third argument or otherwise specifying on the schema the collection name is implied to be “mymodels”. So check that you have the correct collection as well as the correct database connection where you expect the documents to be removed.

Solution 2

The function .remove works only on Mongoose document model instance.This is an example to remove one model :

Model.findOne({ field : 'toto'}, function (err, model) {
    if (err) {
        return;
    }
    model.remove(function (err) {
        // if no error, your model is removed
    });
});

But, if you would remove elements with specific query, you should use the function remove like the find function :

Model.remove({ title : 'toto' }, function (err) {
    // if no error, your models are removed
});

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply