2

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);
})
Wei Chen
  • 69
  • 7

1 Answers1

0

Your console.log(data) is being called before data is being populated. Move your console.log(data) into your if block, like:

if (++collsPrinted == colls.length) {
     db.close();
     console.log(data);
}
developing2020
  • 322
  • 1
  • 9