在循环中使用findOne在Node.js中花费的时间太长 [英] Using findOne in a loop takes too long in Node.js

查看:668
本文介绍了在循环中使用findOne在Node.js中花费的时间太长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB中使用Node.js,我也使用Monk进行数据库访问。我有以下代码:

I'm using Node.js with MongoDB, I'm also using Monk for db access. I have the below code :

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");

我对此代码有两个问题:

I have two questions regarding this code :


  1. 我看到执行时间和文件已保存!首先是字符串,然后我看到控制台中的朋友的名字。这是为什么?我不应该先看到名字然后是执行时间吗?是因为Node.js的异步性质?

  2. 名称在控制台中打印速度非常慢,速度就像两秒钟内的一个名字。为什么这么慢?有没有办法让这个过程更快?

编辑:

打破朋友列表是个好主意小块并异步打电话给朋友?是否会使流程更快?

Is it a good idea to break friends list to smaller pieces and call friends asynchronously? Would it make the process faster?

编辑2:

我将代码更改为:

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

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

这不会出错,但这也不会打印任何内容。

This doesn't give an error, but this doesn't print anything either.

提前致谢。

推荐答案

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
                                    }    
                                });

这篇关于在循环中使用findOne在Node.js中花费的时间太长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆