sprijk
sprijk

Reputation: 423

How to list all MongoDB databases in Node.js?

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.

Upvotes: 14

Views: 13506

Answers (5)

Balasubramanian S
Balasubramanian S

Reputation: 1433

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


Upvotes: 1

Sarvpriy
Sarvpriy

Reputation: 31

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());

Upvotes: 0

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

Upvotes: 13

Rohit Parte
Rohit Parte

Reputation: 4036

*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()

Upvotes: -1

paulmelnikow
paulmelnikow

Reputation: 17208

Use db.admin().listDatabases.

Upvotes: 19

Related Questions