9

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!

3

2 Answers 2

9

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

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

Sign up to request clarification or add additional context in comments.

Comments

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>

1 Comment

Thanks for the response. I did want to do it from the Node.js driver. I updated my question to reflect that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.