在Node.js中循环使用findOne会花费很长时间

发布于 2021-01-31 23:15:02

我将Node.js与MongoDB结合使用,也将Monk用于数据库访问。我有以下代码:

console.time("start");

collection.findOne({name: "jason"},
function(err, document) {

  for(var i = 0; i < document.friends.length; i++) // "friends is an array contains ids of the user's friends"
  {
    collection.findOne({id: document.friends[i]}, function(err, doc)
    {
      console.log(doc.name);
    });
   }

});

console.log("The file was saved!");
console.timeEnd("start");

关于此代码,我有两个问题:

  1. 我看到执行时间,并且“文件已保存!” 首先输入字符串,然后在控制台中看到朋友的名字。这是为什么?我不应该先看名字然后再看执行时间吗?是否因为Node.js的异步特性?
  2. 名称在控制台中的打印速度非常慢,速度就像两秒钟内出现一个名称一样。为什么这么慢?有没有办法使过程更快?

编辑:

将朋友列表细分成较小的块并异步调用朋友是个好主意吗?这样会使过程更快吗?

编辑2:

我将代码更改为此:

collection.find({ id: { "$in": document.friends}}).then(function(err, doc)
{
  console.log(doc.name);

      if(err) {
      return console.log(err);
       }
}

这不会产生错误,但是也不会输出任何内容。

提前致谢。

关注者
0
被浏览
91
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。
    collection.aggregate([
                                    {
                                        $match:{
                                            id :{ "$in" : document.friends},
                                        }
                                    }
                                    ]).exec(function ( e, d ) {
                                        console.log( d )
    
                                        if(!e){
                                            // your code when got data successfully
                                        }else{
                                            // your code when you got the error
                                        }    
                                    });
    


推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看