Reputation: 33
I want to store all collection names of MongoDB in a variable/array. How can I write nodeJS code to do that?
Upvotes: 2
Views: 3503
Reputation: 581
await db.listCollections().toArray().map(c => c.name);
This returns a string array containing the name of every collection.
Upvotes: -1
Reputation: 597
client.db(dbName);
listCollections
method to get detail info of each collection.finally filter and push the required information and close the connection.
const mongo = require('mongodb').MongoClient;
mongo.connect(connectionUrl, function(err, client) {
let allCollections = [];
//create client by providing database name
const db = client.db(dbName);
db.listCollections().toArray(function(err, collections) {
if(err) console.log(err);
//iterate to each collection detail and push just name in array
collections.forEach(eachCollectionDetails => {
allCollections.push(eachCollectionDetails.name);
});
//close client
client.close();
});
});
Upvotes: 4