I just started to check on the Internet how to use momgoose to delete all documents in the collection. But I didn’t find it. I just blogged it down. It’s convenient for myself and others.
It is also possible to use the native statements in mongoDB. But in line with the requirements of the code to be written, it is really unwilling to write this way.
How to use the methods provided by mongoose to delete all documents in the collection in mongoose is listed below.
Code:
They are: Model.remove(Delete document condition, callback function)
.
Example:
// delete all documents // Student is a Model. Student.remove((), function ( err ) { // If the filter condition is empty, it means all console .log( "success" ); });
It can also be like this:
// delete all documents // Student is a Model. Student.remove( function ( err ) { console .log( "success" ); });
The above two methods are related use cases can be found in the official documentation and StackOverFlow.
But my Mongoose version is 5.9.Officially, the above method is a deprecated method. Do not use it anymore. We recommend using another method instead.
Method after 5.9: Model.deleteMany()
// Student is a Model. Student.deleteMany({}, function ( err ) { console .log( "success" ); });