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); } }
Mark Stosberg Mar 17 '17 at 14:33 2017-03-17 14:33
source share