14

I've tried to find a solution to this question in: http://mongodb.github.io/node-mongodb-native/

However, I could not find a solution to listing all available MongoDB databases from a Node.js app.

1
  • I think you can't do it with mongodb-native Commented May 15, 2013 at 17:15

5 Answers 5

19

Use db.admin().listDatabases.

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

Comments

13

You can do this now with the Node Mongo driver (tested with 3.5)

const MongoClient = require("mongodb").MongoClient;

const url = "mongodb://localhost:27017/";
const client = new MongoClient(url, { useUnifiedTopology: true }); // useUnifiedTopology removes a warning

// Connect
client
  .connect()
  .then(client =>
    client
      .db()
      .admin()
      .listDatabases() // Returns a promise that will resolve to the list of databases
  )
  .then(dbs => {
    console.log("Mongo databases", dbs);
  })
  .finally(() => client.close()); // Closing after getting the data

Comments

1

If you are using mongoose, the below code can be used.


import mongoose from 'mongoose';

mongoose.set('strictQuery', true);
mongoose.connect('mongodb://localhost:27017/mydb', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
const db = mongoose.connection;

// Check DB Connection
db.once('open', () => {
  (async () => {
    const data = await mongoose.connection.db.admin().command({
      listDatabases: 1,
    });
    console.log(data);
  })();
  console.log('Connected to MongoDB');
});

// Check for DB errors
db.on('error', (err) => {
  console.log('DB Connection errors', err);
});

export default mongoose;

If you want to get the database list on your other functions, make sure the connection is established first and also make sure the user has admin access and then just do the below query. This is a sample from my API router.

// Get all databases

router.get('/database/get', async (req, res) => {
  try {
    const data = await mongoose.connection.db.admin().command({
      listDatabases: 1,
    });
    if (data && data !== null) {
      res.status(200).send({ data: data });
      return;
    }
    res.status(200).send({ data: null, message: 'Data not found' });
  } catch (e) {
    // eslint-disable-next-line no-console
    console.log(e);
    res.status(500).send(e.message);
  }
});


1 Comment

Out of all the different answers on different forums, this is the only example that actually worked for for this specific case of getting all databases through mongoose. Thank you!
0

Only admins can see all the database. So connect to mongodb database with admin creds then create an admin instance by await db.admin(), then list down all databases await adminDB.listDatabases()

const MongoClient = require('mongodb').MongoClient;
let client = await MongoClient.connect(process.env.MONGO_DB_URL);
const db = await client.db(process.env.DEFAULT_DB_NAME);
let adminDB = await db.admin();
console.log(await adminDB.listDatabases());

2 Comments

Code alone makes for a pretty low quality answer. Could you explain us what your code snippet does?
I think the code is pretty obvious.
-1

*Its difficult to get list by db.admin().listDatabases, below code will work fine in nodejs *

const { promisify } = require('util');
const exec = promisify(require('child_process').exec)
async function test() {
  var res = await exec('mongo  --eval "db.adminCommand( { listDatabases: 1 }         
)" --quiet')
  return { res }
}

test()
  .then(resp => {
    console.log('All dbs', JSON.parse(resp.res.stdout).databases)
  })
test()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.