How to list all MongoDB databases in Node.js?

前端 未结 3 1406
你的背包
你的背包 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 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
    

提交回复
热议问题