How to drop a database with Mongoose?

Mongoose will create a database if one does not already exist on connection, so once you make the connection, you can just query it to see if there is anything in it.

You can drop any database you are connected to:

var mongoose = require('mongoose');
/* Connect to the DB */
mongoose.connect('mongodb://localhost/mydatabase',function(){
    /* Drop the DB */
    mongoose.connection.db.dropDatabase();
});

Tried @hellslam's and @silverfighter's answers. I found a race condition holding my tests back. In my case I'm running mocha tests and in the before function of the test I want to erase the entire DB. Here's what works for me.

var con = mongoose.connect('mongodb://localhost/mydatabase');
mongoose.connection.on('open', function(){
    con.connection.db.dropDatabase(function(err, result){
        done();
    });
});

You can read more https://github.com/Automattic/mongoose/issues/1469


There is no method for dropping a collection from mongoose, the best you can do is remove the content of one :

Model.remove({}, function(err) { 
   console.log('collection removed') 
});

But there is a way to access the mongodb native javascript driver, which can be used for this

mongoose.connection.collections['collectionName'].drop( function(err) {
    console.log('collection dropped');
});

Warning

Make a backup before trying this in case anything goes wrong!


If you modify @hellslam's solution like this then it will work

I use this technique to drop the Database after my integration tests

//CoffeeScript
mongoose = require "mongoose"
conn = mongoose.connect("mongodb://localhost/mydb")

conn.connection.db.dropDatabase()

//JavaScript
var conn, mongoose;
mongoose = require("mongoose");
conn = mongoose.connect("mongodb://localhost/mydb");

conn.connection.db.dropDatabase();

HTH at least it did for me, so I decided to share =)