Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...