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.

3
  • Might be dup question: stackoverflow.com/questions/10390041/… Commented Apr 11, 2017 at 11:57
  • 2
    Why have you commented out the callback() call in save()? That's exactly where it should be called. Commented Apr 11, 2017 at 12:00
  • I guess, i kept forgetting to uncomment the below callback() function. It worked. Stupid me. Commented Apr 11, 2017 at 12:38

1 Answer 1

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();
      });
Sign up to request clarification or add additional context in comments.

1 Comment

It should be inside the callback passed to save(), not passed as a separate argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.