Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 974
AsTeR Avatar asked Jul 22 '14 07:07

AsTeR


2 Answers

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.

like image 123
Neil Lunn Avatar answered Nov 15 '22 22:11

Neil Lunn


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
});
like image 29
throrin19 Avatar answered Nov 15 '22 22:11

throrin19