Reputation: 333
I have a simple case - I want to drop a database if it exists, then I want to create a new one. I use node.js official driver.
Now, I am trying to do it with the following code:
const client = new MongoClient(dbUrl, { useNewUrlParser: true });
client.connect(() => {
const db = client.db();
db.dropDatabase();
createUsers(db);
client.close();
console.log(`Database "${db.databaseName}" created successfully`);
}, (error) => {
if (error) throw error;
});
But I get an error: "Topology was destroyed" from mongodb. But there is no method to create a database after dropping. How can I recreate database correctly?
Upvotes: 0
Views: 376
Reputation: 64
Delete client.close();
Look my code
const {MongoClient} = require('mongodb');
MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true }).then((client) => {
console.log('Connected to MongoDB server')
const dbOld = client.db('db01')
// drop db01
dbOld.dropDatabase().then(() => {
console.log(`${dbOld.databaseName} drop successfully `)
// create db01 again
const dbNew = client.db('db01')
console.log(`${dbNew.databaseName} recreated successfully `);
},e => console.log(e))
})
Good Luck!
Upvotes: 1
Reputation: 333
The finish solution based on @padeq answer:
/**
* Rereates a database
* @param {String} dbUrl Database url
*/
const recreateTestDb = (dbUrl) => {
MongoClient.connect(dbUrl, { useNewUrlParser: true }).then((client) => {
const currentDb = client.db();
currentDb.dropDatabase().then(() => {
const newDb = client.db();
createUsers(newDb);
client.close().then(() => {
console.log(`New database "${newDb.databaseName}" recreated successfully`);
});
});
});
};
Upvotes: 0