【问题标题】:How to list all MongoDB databases in Node.js?如何在 Node.js 中列出所有 MongoDB 数据库?
【发布时间】:2021-10-04 21:49:12
【问题描述】:

我试图在http://mongodb.github.io/node-mongodb-native/中找到解决这个问题的方法

但是,我找不到从 Node.js 应用程序列出所有可用 MongoDB 数据库的解决方案。

【问题讨论】:

  • 我认为你不能用mongodb-native来做到这一点

标签: node.js mongodb


【解决方案1】:

【讨论】:

    【解决方案2】:

    您现在可以使用 Node Mongo 驱动程序(使用 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
    

    【讨论】:

      【解决方案3】:

      只有管理员可以查看所有数据库。因此,使用管理员凭据连接到 mongodb 数据库,然后通过 await db.admin() 创建一个管理员实例,然后列出所有数据库 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());
      

      【讨论】:

      • 仅代码就可以得到相当低质量的答案。你能解释一下你的代码 sn-p 是做什么的吗?
      • 我觉得代码很明显。
      【解决方案4】:

      *db.admin().listDatabases 很难获取列表,下面的代码在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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-29
        • 1970-01-01
        • 1970-01-01
        • 2014-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-24
        相关资源
        最近更新 更多