5

I have seen answers on C# and Java but not able to find anything on NodeJs. I have tried using cmd shell in Windows to get the required output but no luck.

I am aware that the same information can be taken in Mongo shell but the requirement is to get a list within the NodeJs app.

 cmd = child_process.exec('"C:\\Program Files\\MongoDB\\Server\\3.2\\bin\\mongo.exe" admin ; db.getMongo().getDBNames()');

and also

var mongoServer = require('mongodb-core').Server;

 var server = new mongoServer({
    host: 'localhost'
    , port: 27017
    , reconnect: true
    , reconnectInterval: 50   });

  server.on('connect', function (_server) {

  console.log('connected');

 var cmdres = _server.command('db.adminCommand({listDatabases: 1})');

 console.log("Result: " + cmdres);

}

1

2 Answers 2

9

You can use mongodb driver to get dbs as following

var MongoClient = require('mongodb').MongoClient;

// Connection url
var url = 'mongodb://localhost:27017/test';
// Connect using MongoClient
MongoClient.connect(url, function(err, db) {
  // Use the admin database for the operation
  var adminDb = db.admin();
  // List all the available databases
  adminDb.listDatabases(function(err, result) {
    console.log(result.databases);
    db.close();
  });
});

Reference: http://mongodb.github.io/node-mongodb-native/2.2/api/

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

Comments

3

See this answer

db.admin().listDatabases

3 Comments

console.log(db.admin().listDatabases()); returns Promise { <pending> }. Could you suggest how I should use your code to get data?
db.admin().listDatabases().then(function(databases){console.log(databases});
That command returns a promise, because you didn't provide a callback function argument to listDatabases(). The MongoDB node.js driver functions all operate in this manner - the function callback argument is optional. If that function callback is supplied, then the function operates in conventional node.js callback fashion, and executes your callback when the function operation is completed. OMIT the function callback argument, and the function returns a Promise.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.