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:
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.
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With