javascript - 增量计数器在 Node JS 中过早打印
问题描述
我正在将 157 个文档从 1 个集合复制到另一个集合。我只想计算插入或跳过了多少文档,但它总是给出错误的输出(比如只有 100,但它应该是 157,因为目标列是空的,现在插入了所有 157)。任何帮助将不胜感激。
var cursor = await collection.find(query).project(projection);
var countInserted = 0;
var countSkipped = 0;
await cursor.forEach(async function(i) {
i.ts_imported = new Date();
//console.log(i);
ret = await EmptyCollection.updateOne(
{ URL: i.sourceURL },
{
$setOnInsert: {
URL: i.sourceURL,
status: 0,
remarks: "in the run got 0 jobs",
collection: col
}
},
{ upsert: true }
);
if (await ret.upsertedCount == 0) {
++countSkipped;
}
else {
++countInserted;
}
//console.log(countInserted); //This shows actual count.
});
console.log(countInserted); //This shows wrong count.
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(countInserted+' rows inserted.<br/>'+countSkipped+" rows skipped.");
res.end();
解决方案
尝试使用传统for(;;;)
语法代替forEach
,这可能会解决您的问题!
推荐阅读
- kubernetes - 使用 kubernetes 执行器时找不到 Airflow-dag_id 问题
- docker - 带有入口控制器的动态路由
- javascript - 如何创建动态 HTML 文件并使用 javascript 将其发送到电子邮件
- c# - SSL 证书格式
- c# - Quickbooks Online API - 提供发票 ID 时付款“未应用”
- java - OSGi 中仅运行时依赖项的最佳实践
- html - 我的页脚不在页面底部
- c++ - 我使用增量时间和插值的固定时间步的解决方案是否错误?
- java - Java Scanner: InputMismatchException - 无法使用 next() 和 hasNext() 方法读取多行的 CSV 文件:
- prolog - Prolog:将列表成员与前一个成员相乘