我试图遍历集合内部的所有文档,并存储在全局var中,但是看起来push()无法正常工作,并在toArray()内部返回空数组[], 有什么建议吗?
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);
})
答案 0 :(得分:0)
在填充console.log(data)
之前,将调用您的data
。将console.log(data)
移到if
块中,例如:
if (++collsPrinted == colls.length) {
db.close();
console.log(data);
}