0

My aim is to save records in a mongoDB collection being in a async foreach loop. Below is the code which speaks for itself.

async.forEach(data, function(item, callback) {
      var object = new Collection_Object();

      // errorLog.push(sdb);
      object.save(function(error) {
        count++;
        console.log(count);
        if(error) {
          console.log("inside error");
          count--;
        }
        //callback();
      });
      callback();
    }, function() {
    //This is the block which should be called after foreach. 
      res.json(data);
  });

Now what is happening is the flow skips the save part and directly jumps to the block which should be called after forEach.

If i am commenting the save part, as expected the callback is working properly. I don't see where i am doing mistake. May be collection.save() isn't suppose to be like this. Please guide.

bibliophilsagar
  • 1,713
  • 1
  • 19
  • 40

1 Answers1

1

object.save() is also async, so you have to use callback function with save method, like:

object.save(function(error) {
        count++;
        console.log(count);
        if(error) {
          console.log("inside error");
          count--;
        }
        callback();
      });
Alessandro
  • 4,382
  • 8
  • 36
  • 70