I want to store all collection names of MongoDB in a variable/array. How can I write nodeJS code to do that?
-
1You are expected to have some attempt at a solution included in your question, for people to see what your understanding of the problem is and to give them a starting point for a solution. Have a look at How to Ask and check out the tourZoey Hewll– Zoey Hewll2017-10-10 15:55:24 +00:00Commented Oct 10, 2017 at 15:55
-
1Possible duplicate of Listing all collections in a mongo database within a nodejs scriptuser400654– user4006542017-10-10 22:04:52 +00:00Commented Oct 10, 2017 at 22:04
Add a comment
|
2 Answers
- create a connection by providing connection url.
- create a client to db using database name
client.db(dbName); - call
listCollectionsmethod 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(); }); });