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
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: {} }
});
const collections = Object.keys(mongoose.connection.collections);
this gives you a JSON document of your collections.
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());
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());