0

我正在将 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();
4

3 回答 3

0

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

于 2020-05-27T06:33:10.483 回答
0

诸如 、 和 之类的数组处理函数forEachmap不能filterreduceasync/await 一起使用。您将需要使用for循环或while循环:

       for (x=0; x<cursor.length; x++) {
           let i = cursor[x];
            i.ts_imported = new Date();
            //console.log(i);
            let ret = await EmptyCollection.updateOne({"URL":i.sourceURL},{$setOnInsert: {"URL": i.sourceURL, "status" :0 , "remarks" :"in the run got 0 jobs", "collection" : col}},{ upsert: true });

            // ...
于 2020-05-27T06:35:31.347 回答
0

谢谢你们试图帮助我并表现出兴趣。但我自己找到了答案。我只需要使用“Promise”来实现它,如下所示-


    var cursor = await collection.find(query).project(projection);
                var countInserted = 0;
                var countSkipped = 0;
                var arr = await cursor.toArray();
                await Promise.all(
                    arr.map(async 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;
                        }
                    })
                );

于 2020-05-27T06:55:15.340 回答