I was try to loop through all documents that inside of collections, and store in a global var, but it looks like the push() is not working and return empty array [] inside of toArray(), any suggestion?
const mongo = require('mongodb');
const url = 'mongodb://localhost:27017/test'
var data = [];
const collections = mongo.connect(url, { useNewUrlParser: true }, (err, db) => {
console.log('connection success');
db.db().listCollections().toArray((err, colls) => {
var collsPrinted = 0;
colls.forEach(element => {
db.db().collection(element.name).find().sort({"_id":-1}).limit(1).toArray((err, doc) => {
data.push(doc);
if (++collsPrinted == colls.length) db.close();
});
});
});
console.log(data);
})