How to list all MongoDB databases in Node.js?

前端 未结 3 1392
你的背包
你的背包 2020-12-17 19:18

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 Mongo

相关标签:
3条回答
  • 2020-12-17 19:57

    Use db.admin().listDatabases.

    0 讨论(0)
  • 2020-12-17 20:03

    *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()
    
    0 讨论(0)
  • 2020-12-17 20:22

    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
    
    0 讨论(0)
提交回复
热议问题