Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

javascript - Using findOne in a loop takes too long in Node.js

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. I see the execution time and "The file was saved!" string first, then I see the names of the friends coming in the console. Why is that? Shouldn't I see the names first then the execution time? Is it because the async nature of Node.js?
  2. Names are printing very slowly in the console, the speed is like one name in two seconds. Why is it so slow? Is there a way to make the process faster?

EDIT:

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

EDIT 2:

I changed my code to this :

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.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Answer for question 1: Yes, you are right.

Is it because the async nature of Node.js.

And to prevent that Node.js provides some mechanism for that you can use it otherwise you can do it on your own manually by setting one flag.

Answer for question 2:

you can use $in instead of findOne, it will be ease and fast.

e.g. .find({ "fieldx": { "$in": arr } })

arr :- In this you need to provide whole array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...