简体   繁体   中英

How to recreate a mongo database with using Node.js mongodb official provider?

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?

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!

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`);
      });
    });
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM