0

I want to save data to MongoDB. But, before saving, I need to verify if a document with a certain id already exists. The document will not be saved if it exists.
And I try to use the count() method for it. But, I don't understand why the i variable increased inside the count() method callback function. The argument per_page = 1.

function storeData (data, per_page) {
  var i;
  for(i = 0; i < per_page; i++) {

    console.log("Before i = " + i);

    CoubVideo.count({id: data.coubs[i].id}, function (err, count) {

      console.log("After i = " + i);

      if (count == 0) {
        var video = new CoubVideo(data.coubs[i]);

        video.save(function (err) {
          if (err) throw err;
          console.log("Saved successfully!");
        });
      } else { 
        console.log("Duplicate");
      }

    });
  }
}

Script output:

Before i = 0;
After i = 1;
Saved successfully!
srgbnd
  • 5,404
  • 9
  • 44
  • 80
  • 1
    This [question (and its answer)](http://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop) explain what is going on. Its because your call to `CoubVideo.count` is asynchronous and by the time the callback is called, the `i++` has already been executed. – go-oleg May 08 '16 at 22:39
  • Thank you. So, what is the best way to make the iteration and the `count()` method synchronous? Passing `i` var as an argument to the callback function? – srgbnd May 09 '16 at 07:36
  • @go-oleg I've got it. Please post your answer and I will vote. – srgbnd May 09 '16 at 07:40

0 Answers0