我正在尝试在一个数据库中搜索所有集合,但我不知道如何在forEach循环结束时返回数据。 我知道这是Promise或async / await的地方,但不知道如何在forEach之后正确使用它: - (
//db.js
var MongoClient = require('mongodb').MongoClient;
module.exports = {
searchAllCollections: function() {
return MongoClient.connect('mongodb://localhost:27017/nodeLists', {poolSize: 10}).then(function(db) {
var ipList = [];
db.listCollections().forEach((doc) => {
console.log(doc.name);
db.collection(doc.name).find({ip: "192.168.0.1"}).toArray((err, data) => {
console.log(data);
ipList.push(data);
});
});
});
}
};
//app.js
var db = require('./db');
db.searchAllCollections().then(function(items) {
console.info('Returned data:',items);
}, function(err) {
console.error('The promise was rejected', err, err.stack);
});