Is there a way to check if a database exists in Mongo from the Node.js driver?

14,744

Solution 1

Check if db.admin().listDatabases contains the database name.

If the server has authorization enabled, you will need the appropriate permissions.

Solution 2

The easiest way to tell whether a database exists would be from the mongo she'll. To list all databases available, enter the following into your Mongo shell.

show dbs

To list the database you're currently using, enter:

db

To explicitly select a database, enter:

use <database>
Share:
14,744
Jorge Silva
Author by

Jorge Silva

Updated on July 25, 2022

Comments

  • Jorge Silva
    Jorge Silva almost 2 years

    I'm finding it surprisingly difficult to see find a way to see if a database exists or not in MongoDB from the Node.js driver. There seems to be no method in the Node.js driver to check if a database exists.

    For example, the following doesn't throw an error:

    var mongo = require('mongodb').MongoClient;
    
    mongo.connect({ 'mongodb://localhost:27017/databaseThatDoesntExists }, function (err, db) {
       // There is no error
       if (err) console.log(err);
       // Let's get some stats on a database that doesn't exist
       db.statsAsync(function (err, result) {
          console.log(result);
       });
    });
    

    Results will be an object like this:

    { db: 'databaseThatDoesntExist',
      collections: 0,
      objects: 0,
      avgObjSize: 0,
      dataSize: 0,
      storageSize: 0,
      numExtents: 0,
      indexes: 0,
      indexSize: 0,
      fileSize: 0,
      ok: 1 }
    

    Can you check to see if a database exists in MongoDB form the Node.js driver? Is there even a concept of a database existing in MongoDB? Is referencing a database that doesn't exist just referencing a database with no collections?

    Mongo, why can't you just throw an error! I like when my code throws errors!