I'm attempting to loop through all documents within collections, store them in a global variable, but it seems like the push() function is not working and returning an empty array [] inside of toArray(). Any ideas?
const mongo = require('mongodb');
const url = 'mongodb://localhost:27017/test'
var data = [];
const collections = mongo.connect(url, { useNewUrlParser: true }, (err, db) => {
console.log('connection successful');
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);
})