Mongoose Model.remove (callback) does not remove anything from my collection

I am trying to remove all content from a Mongoose database, but nothing works.

I 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 deleting the .find() step or adding .exec() my callback is never displayed, and my data is still here.

I am sure my model and connection are ok:

  • I see the links in Mongo magazine
  • I can add documents by manipulating the same model elsewhere

Related: How to delete documents using Node.js Mongoose?

EDIT

My problem was caused by a syntax error that did not display. The selected answer works as well as the code above. Moderators can delete my question if it seems necessary.

+8
javascript mongodb mongoose
source share
2 answers

This is not a query object returned by Mongoose, the only valid method is .remove() :

 MyModel.remove(function(err,removed) { // where removed is the count of removed documents }); 

This is the same as:

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

Also, how do you determine which documents are not deleted? Perhaps he is looking for the wrong collection. Mongoose pluralizes the default collection name unless you explicitly specify the collection name as in:

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

Without this third argument or other indication in the schema, the collection name is implied as "mymodels". Therefore, make sure that you have the correct collection, as well as the correct connection to the database, where you expect documents to be deleted.

+20
source share

The .remove function only works with an instance of the Mongoose instance model. 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 remove items with a specific request, you should use the remove function as the find function:

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

All Articles