Listing all collections in a mongo database within a nodejs script

前端 未结 4 1029
春和景丽
春和景丽 2020-12-09 15:22

I have found a few answers for listing collections in the shell but all the answers I have found for listing collections in a nodejs script seem to have been deprecated, ans

相关标签:
4条回答
  • 2020-12-09 15:57

    In the 2.0 version of the MongoDB driver for node.js you can use listCollections to get a cursor that contains the information of all collections. You can then call toArray on the cursor to retrieve the info.

    db.listCollections().toArray(function(err, collInfos) {
        // collInfos is an array of collection info objects that look like:
        // { name: 'test', options: {} }
    });
    
    0 讨论(0)
  • 2020-12-09 16:02
    const collections = Object.keys(mongoose.connection.collections); 
    

    this gives you a JSON document of your collections.

    0 讨论(0)
  • 2020-12-09 16:06

    If you have access to async/await, it is much cleaner to promisify toArray on the iterator and not use a callback.

    static toArray(iterator) {
      return new Promise((resolve, reject) => {
        iterator.toArray((err, res) => {
          if (err) {
            reject(err);
          } else {
            resolve(res);
          }
        });
      });
    }
    
    const myArray = await toArray(db.listCollections());
    
    0 讨论(0)
  • 2020-12-09 16:13

    Here is a full example on how you do it with the 3.4 version of the Mongo driver for node

    const MongoClient = require("mongodb").MongoClient;
    
    // Connection url
    var url = 'mongodb://localhost:27017/test';
    const client = new MongoClient(url, { useUnifiedTopology: true }); // { useUnifiedTopology: true } removes connection warnings;
    
    const dbName = "test";
    
    client
          .connect()
          .then(
            client =>
              client
                .db(dbName)
                .listCollections()
                .toArray() // Returns a promise that will resolve to the list of the collections
          )
          .then(cols => console.log("Collections", cols))
          .finally(() => client.close());
    
    0 讨论(0)
提交回复
热议问题