【问题标题】:Getting list of all databases with Mongoose使用 Mongoose 获取所有数据库的列表
【发布时间】:2013-01-27 04:03:33
【问题描述】:

有一些类似的问题,但都涉及使用MongoDB NodeJS driver 而不是Mongoose ODM

我阅读了the docs,但找不到这样的功能。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您无法直接从 mongoose 提供的连接中获取列表,但使用 mongo Admin 对象很容易,因为它包含一个名为 listDatabases 的函数:

    var mongoose = require('mongoose')
        , Admin = mongoose.mongo.Admin;
    
    /// create a connection to the DB    
    var connection = mongoose.createConnection(
        'mongodb://user:pass@localhost:port/database');
    connection.on('open', function() {
        // connection established
        new Admin(connection.db).listDatabases(function(err, result) {
            console.log('listDatabases succeeded');
            // database list stored in result.databases
            var allDatabases = result.databases;    
        });
    });
    

    【讨论】:

      【解决方案2】:

      使用 mongoose(版本 6.10.*)获取所有 mongo 数据库列表的一种非常现代的方法是创建一个 mongoose 连接以连接到 Mongo 的管理数据库确保您有一个管理员用户

      Mongoose 对象是一个非常复杂的对象。列出数据库:

      const connection = `mongodb://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${hostname}:${port}/admin`
      

      mongoose 是一个非常复杂的对象,承诺执行多个功能。列出数据库:

      mongoose.connect(connection,  {  useNewUrlParser: true ,  useUnifiedTopology: true }).then( (MongooseNode) => { 
      
      /* I use the default nativeConnection object since my connection object uses a single hostname and port. Iterate here if you work with multiple hostnames in the connection object */
                          
      const nativeConnetion =  MongooseNode.connections[0]
      
      //now call the list databases function
          new Admin(nativeConnetion.db).listDatabases(function(err, results){
              console.log(results)  //store results and use
          });
      })
      

      结果:

      { databases:
         [ { name: 'admin', sizeOnDisk: 184320, empty: false },
           { name: 'config', sizeOnDisk: 73728, empty: false },
           { name: 'local', sizeOnDisk: 73728, empty: false },
           { name: 'test', sizeOnDisk: 405504, empty: false } ],
        totalSize: 737280,
        ok: 1 }
      

      【讨论】:

      • 从哪里导入 Admin?
      【解决方案3】:

      尝试运行this code。原文来自Gist

      【讨论】:

      • 我认为他正在寻找可用数据库的名称,而不是集合。
      猜你喜欢
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多