Reputation: 3691
In my end to end tests, I want to drop the "test" database, and then create a new test db. Dropping an entire database is simple:
mongoose.connection.db.command( {dropDatabase:1}, function(err, result) {
console.log(err);
console.log(result);
});
But now how do I now create the test db? I can't find a createDatabase
or useDatabase
command in the docs. Do I have to disconnect and reconnnect, or is there a proper command? It would be bizarre if the only way to create a db was as a side effect of connecting to a server.
update
I found some C# code that appears to create a database, and it looks like it connects, drops the database, connects again (without disconnecting?) and that creates the new db. This is what I will do for now.
public static MongoDatabase CreateDatabase()
{
return GetDatabase(true);
}
public static MongoDatabase OpenDatabase()
{
return GetDatabase(false);
}
private static MongoDatabase GetDatabase(bool clear)
{
var connectionString = ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString;
var databaseName = GetDatabaseName(connectionString);
var server = new MongoClient(connectionString).GetServer();
if (clear)
server.DropDatabase(databaseName);
return server.GetDatabase(databaseName);
}
Upvotes: 0
Views: 1572
Reputation: 146014
mongodb will create (or recreate) it automatically the next time a document is saved to a collection in that database. You shouldn't need any special code and I think you don't need to reconnect either, just save a document in your tests and you should be good to go. FYI this same pattern applies to mongodb collections - they are implicit create on write.
Upvotes: 2