I am trying to drop an entire database using mongoose. I have tried this answer here, but it only suggests dropping individual collections, not actually answering the question.
I tried making a sample javascript to see what is wrong:
var url = 'mongodb://localhost:27017/ngl_dev'
var mongoose = require('mongoose');
mongoose.connect(url);
// Trying to drop the entire database, doesn't work
/*
mongoose.connections[0].db.dropDatabase(function(err){
if(err){
console.log(err);
}
console.log("Database dropped");
});
*/
// But dropping individual collections does.
/*
mongoose.connections[0].collections.TestTypes.drop(function(err){
if(err){
console.log(err);
}
console.log('Collection dropped');
});
*/
// I can drop the entire database using mongodb module, but I don't have
// access to it in my production code, so this is just an example.
/*
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, db){
if(err){
console.log(err);
}
console.log('Connected to the server');
db.dropDatabase();
console.log('Dropped database');
db.close();
});
*/
When I uncomment the first section, nothing happens, the script hangs, and all the data in the collections and the collections themselves still remain, contrary to what I would expect to happen from running that function.
When I uncomment the second section, I get an error saying that the collection TestType
is undefined, which I guess makes sense since I'm not using the mongoose schema provided in the application. So when I run the same code and require the right schemas, collection dropped
gets printed to the console, the data in the specified collection gets dropped, but the collection itself still remains and the script hangs.
When I uncomment the third section, the specified database actually gets dropped, which is what I would expect to happen for the first section of code. However, this script is being run in a different section of the production code that doesn't have direct access to the mongodb
module, so this is just an example to show that mongoose is not working correctly.
How can I get mongoose to drop the entire database with the dropDatabase()
function?
Essentially what I am trying to do is replace a bash script that uses the mongo shell with something that works cross platform.