How to delete a database using Mongoose?

I am preparing to create a database script in Node.js and Mongoose. How can I check if a database exists, and if so, delete (delete) it using Mongoose?

I could not find a way to drop it using Mongoose.

+72
mongodb mongoose
Apr 10 '12 at 0:12
source share
11 answers

There is no way to remove a collection from mongoose, the best you can do is delete the contents of one of them:

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

But there is a way to access the mongodb embedded javascript file that you can use to do this

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

Warning

Make a backup before trying to do this if something goes wrong!

+128
Apr 10 2018-12-12T00:
source share

Mongoose will create the database if it does not already exist when connecting, so after connecting you can simply query it to see if there is anything in it.

You can delete any database that 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(); }); 
+57
Apr 29 '12 at 2:25
source share

If you change @hellslam's solution like this, 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 this is for me, so I decided to share =)

+11
Jun 04 2018-12-12T00:
source share

Tried the answers @hellslam and @silverfighter. I found a race condition holding my tests. In my case, I run mocha tests and in the previous test function I want to erase the entire database. Here is 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

+8
Jul 12 '15 at 9:27
source share

The difficulty I came across with other solutions is that they rely on restarting the application if you want indexes to work again.

For my needs (i.e., having the ability to run unit test the nuclear blocks of all collections, then recreate them together with my indexes), I decided to implement this solution:

It relies on the underscore.js and async.js libraries to build indexes in parellel, it can be unwound if you are against this library, but I leave it as a simulator for the developer.

 mongoose.connection.db.executeDbCommand( {dropDatabase:1}, function(err, result) { var mongoPath = mongoose.connections[0].host + ':' + mongoose.connections[0].port + '/' + mongoose.connections[0].name //Kill the current connection, then re-establish it mongoose.connection.close() mongoose.connect('mongodb://' + mongoPath, function(err){ var asyncFunctions = [] //Loop through all the known schemas, and execute an ensureIndex to make sure we're clean _.each(mongoose.connections[0].base.modelSchemas, function(schema, key) { asyncFunctions.push(function(cb){ mongoose.model(key, schema).ensureIndexes(function(){ return cb() }) }) }) async.parallel(asyncFunctions, function(err) { console.log('Done dumping all collections and recreating indexes') }) }) }) 
+5
Mar 27 '13 at 19:26
source share

To delete a specific collection in the database:

 model.remove(function(err, p){ if(err){ throw err; } else{ console.log('No Of Documents deleted:' + p); } }); 

Note:

  • Select a model related to a specific scheme (the collection scheme you want to delete).
  • This operation will not remove the collection name from the database.
  • This deletes all documents in the collection.
+4
Jul 03 '13 at 12:48 on
source share

This works for me starting with Mongoose v4.7.0 :

 mongoose.connection.dropDatabase(); 
+3
Nov 30 '16 at 0:17
source share

The best way to dump a database in Mongoose depends on which version of Mongoose you are using. If you are using a version of Mongoose that is 4.6.4 or later, then this method added in this release will most likely work well for you:

 mongoose.connection.dropDatabase(); 

In older versions, this method did not exist. Instead, you should use a direct call to MongoDB:

 mongoose.connection.db.dropDatabase(); 

However, if this was started immediately after the connection to the database was created, perhaps this may happen with an error. This is because the connection is indeed asynchronous and is not configured when the command is executed. This is usually not a problem for other Mongoose calls, such as .find() , which stand until the connection is opened and started.

If you look at the source code for the dropDatabase() shortcut that was added, you will see that it was designed to solve this particular problem. It checks if the connection is open and the connection is ready. If so, he immediately runs the command. If not, it registers a command to start when opening a database connection.

Some of the recommendations above recommend that you always put your dropDatabase command in an open handler. But this only works if the connection is not already open.

 Connection.prototype.dropDatabase = function(callback) { var Promise = PromiseProvider.get(); var _this = this; var promise = new Promise.ES6(function(resolve, reject) { if (_this.readyState !== STATES.connected) { _this.on('open', function() { _this.db.dropDatabase(function(error) { if (error) { reject(error); } else { resolve(); } }); }); } else { _this.db.dropDatabase(function(error) { if (error) { reject(error); } else { resolve(); } }); } }); if (callback) { promise.then(function() { callback(); }, callback); } return promise; }; 

Here is a simple version of the above logic that can be used with earlier versions of Mongoose:

 // This shim is backported from Mongoose 4.6.4 to reliably drop a database // http://stackoverflow.com/a/42860208/254318 // The first arg should be "mongoose.connection" function dropDatabase (connection, callback) { // readyState 1 === 'connected' if (connection.readyState !== 1) { connection.on('open', function() { connection.db.dropDatabase(callback); }); } else { connection.db.dropDatabase(callback); } } 
+3
Mar 17 '17 at 14:33
source share

To delete all documents in a collection:

 myMongooseModel.collection.drop(); 

as shown in tests

0
Apr 6 '17 at 0:09
source share

Mongoose 4.6.0 +:

 mongoose.connect('mongodb://localhost/mydb') mongoose.connection.once('connected', () => { mongoose.connection.db.dropDatabase(); }); 

Passing a callback to connect will no longer work:

TypeError: Cannot read 'commandsTakeWriteConcern' properties from null

0
Aug 07 '17 at 9:54 on
source share

Updated answer for 4.6.0+ if you have a preference for promises ( see docs ):

 mongoose.connect('mongodb://localhost/mydb', { useMongoClient: true }) .then((connection) => { connection.db.dropDatabase(); // alternatively: // mongoose.connection.db.dropDatabase(); }); 

I tested this code in my own code using mongoose 4.13.6. Also note the use of the useMongoClient option ( see Docs ). The documents indicate:

Mongoose's default connection logic has been deprecated since 4.11.0. Please select a new connection logic using the useMongoClient option, but first check your connections if you are updating an existing code base!

0
Dec 12 '17 at 18:46 on
source share



All Articles