I want to store all collection names of MongoDB in a variable/array. How can I write nodeJS code to do that?
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(); }); });
await db.listCollections().toArray().map(c => c.name);
这将返回一个包含每个集合名称的字符串数组。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.