eChung00
eChung00

Reputation: 631

how to clear mongoDB using mongoose for node.js app

I am trying to clear mongoDB using mongoose. specifically, what I am trying to do is to clear out all data before each test for my node.js app. Let's say I have a db called "User" and in this db have several collections. With given mongoose instance, how do I clear out all data? I have tried searching about this but all the answers did not work for me..

Upvotes: 1

Views: 146

Answers (1)

Alexander Jeyaraj
Alexander Jeyaraj

Reputation: 833

You just need to drop the database. Here is the code that will do it.

function dropDatabase(name, cb) {
    var mongoose = require('mongoose');
    var con = mongoose.createConnection('mongodb://localhost/' + name);
    con.on('connected', function(err) {
        if (!err) {
            con.db.dropDatabase(function(err) {
               cb(err);
            });
        } else {
            cb(err);
        }
    });
};

"name" is the name of the database. You can call it like dropDatabase("User", function(err) {});

Upvotes: 1

Related Questions