使用带有Node(v9.8.0)的Nodejs(3.0.4)的MongoDB客户端时遇到问题。 问题在于,当我对数据库运行查询时,它在一次调用时有效,但在循环调用时无效。
请参阅以下代码:
'use strict';
// Load modules
const Mongo = require('mongodb');
const MongoClient = Mongo.MongoClient;
async function runOnce() {
let result = await runBasicMongoQuery();
console.log(result);
process.exit(0);
}
async function runManyTimes() {
[1,2,3,4,5].forEach(async (x) => {
let result = await runBasicMongoQuery();
console.log(result);
});
process.exit(0);
}
async function runBasicMongoQuery() {
try {
console.log(`Creating client:`);
let client = await MongoClient.connect('mongodb://localhost:27017/test');
console.log(`\tclient: ${!!client}`);
console.log(`Creating db:`);
let db = client.db();
console.log(`\tdb: ${!!db}`);
console.log(`Retrieve collection:`);
let coll = db.collection('temp');
console.log(`\tcoll: ${!!coll}`);
console.log(`Run Query:`);
let result = await coll.find({ name: 'me' }).sort({ name: 1 }).toArray();
console.log(`\tresult: ${!!result}`);
return result;
} catch(err) {
console.log(err);
}
}
当我运行函数runOnce()
时,我获得了成功的执行:
Creating client: client: true Creating db: db: true Retrieve collection: coll: true Run Query: result: [ { _id: 5aabfc0763abc840a19d927c, name: 'me' } ]
当我运行命令runManyTimes()
时,我收到以下回复:
Creating client: Creating client: Creating client: Creating client: Creating client:
请注意,这在MongoClient.connect(...)中无声地失败。没有错误,没有任何错误。
为什么在使用async / await的循环中调用命令会失败?
感谢。
答案 0 :(得分:1)
它不是关于MongoDB,而是关于您在.forEach()
循环中执行的任何异步调用,请检查此question。
在您的特定情况下,我不认为它失败了,process.exit(0)
只是在您取回结果之前强制退出流程。