首页 > 解决方案 > 增量计数器在 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();

标签: javascriptnode.jsasync-await

解决方案


尝试使用传统for(;;;)语法代替forEach,这可能会解决您的问题!


推荐阅读