I'm trying to print list of database names following their corresponding collection names using a nested loop with MongoDB Node.js Driver.
Database A:
Collection a
Collection b
Database B:
Collection f
Collection g
Database C:
Collection h
Collection j
but instead I get this:
Database A:
Database B:
Database C:
Collection a
Collection b
Collection f
Collection g
Collection h
Collection j
What am I doing wrong? Is this because listDatabases()
and listCollections()
sharing the same MongoClient connection and they can't be executed simultaneously or it is just promise
thing?
const mongo = require('mongodb').MongoClient;
const url = 'mongodb://127.0.0.1:27017';
mongo.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, client) => {
if (err) {
console.log(err)
return;
}
// print db names with their corresponding collections
client.db().admin().listDatabases({ nameOnly: true }, (err, result) => {
if (!err) {
result.databases.forEach((db) => {
console.log('Database: ' + db.name);
client.db(db.name).listCollections().toArray((err, collections) => {
collections.forEach((col) => {
console.log(col.name);
});
});
});
} else {
return console.log(err.message);
}
});
});