简体   繁体   中英

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

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!

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

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

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>

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