How to get list of databases in MongoDB using NodeJs? [duplicate]

主宰稳场 提交于 2021-02-10 07:44:35

问题


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:


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/




回答2:


See this answer

db.admin().listDatabases



来源:https://stackoverflow.com/questions/39748101/how-to-get-list-of-databases-in-mongodb-using-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!