简体   繁体   中英

MongoDB: How to read all documents from all collections use expressjs?

i have a mongodb with multiple documents inside of multiple collections, and I want to loop through everyone of it. Below is my code,

const mongo = require('mongodb');
const url = 'mongodb://localhost:27017/test'

mongo.connect(url,{ useNewUrlParser: true },  data, (err, db)=>{
    console.log('connection success');

    db.db().listCollections().toArray(function(err, colls) {
        colls.forEach(element => {
            db.db().collection(element.name.toString()).find().toArray((err, doc) => {
                console.log(doc);
            });
        });
    });

    db.close();
})
}

this is what I get back from listCollections()

[ ....,
{ name: 'documetn1',
type: 'collection',
options: {},
info: { readOnly: false, uuid: [Binary] },
idIndex:
 { v: 2, key: [Object], name: '_id_', ns: 'test.documetn1' } }, 
...]

somehow i am getting null for below

db.db().collection(element.name.toString()).find().toArray((err, doc) => {
                    console.log(doc);
                });

need help here!

I've tried your code and each collection find return at err "MongoError: Topology was destroyed" . As Carlos Rodríguez said in this answer to a question related to this error It seems it's due to an early db.close() so it could get fixed doing this, for example:

const mongo = require('mongodb');
const url = 'mongodb://localhost:27017/test'

mongo.connect(url, { useNewUrlParser: true },  data, (err, db) => {
    console.log('connection success');

    db.db().listCollections().toArray((err, colls) => {
        var collsPrinted = 0;
        colls.forEach(element => {
            db.db().collection(element.name).find().toArray((err, doc) => {
                console.log(doc);
                if (++collsPrinted == colls.length) db.close();
            });
        });
    });
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM