我有一个mongobd,其中有多个集合中的多个文档,我想遍历每个文档。下面是我的代码,
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();
})
}
这是我从listCollections()中得到的
[ ....,
{ name: 'documetn1',
type: 'collection',
options: {},
info: { readOnly: false, uuid: [Binary] },
idIndex:
{ v: 2, key: [Object], name: '_id_', ns: 'test.documetn1' } },
...]
不知何故,我在下面没有空
db.db().collection(element.name.toString()).find().toArray((err, doc) => {
console.log(doc);
});
需要帮助!
答案 0 :(得分:1)
我已经尝试了您的代码,并且每个集合都在err
"MongoError: Topology was destroyed"
找到了返回值。就像卡洛斯·罗德里格斯(CarlosRodríguez)在this answer to a question related to this error中所说的那样,这似乎是由于db.close()
太早了,所以可以对此进行修正,例如:
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();
});
});
});
})