How do I make sure a looping save to the database executes before done() in Mocha?

Problem

I am running the following code as a parameter to before() to create test entries in my MongoDB database (using Mongoose). However, this results in an error because done() is called multiple times. However, if I don't use done(), then the testPhoto won't save to the database because it is handed off to a background thread.

var createFeed = function(done) {
  for (var i = 1; i <= 10; i++) {
    var testPhoto = new Photo({ owner   : 'test' + (i % 2),
                            caption : 'test caption',
                            ratings : [{ _id   : 'test' + (i % 3),
                                        rating : 5 }] });
    testPhoto.save(done);
  }
}

Is there any way to guarantee that the done() function executes only once, after all the testPhoto's have been saved to the database?

Problem courtesy of: ArKi

Solution

You can do something more formal with async, or you can take a simpler approach where you just keep track of the number of save operations outstanding and call done when they've all completed:

var createFeed = function(done) {
  var saves = 10;
  for (var i = 1; i <= 10; i++) {
    var testPhoto = new Photo({ owner : 'test' + (i % 2),
                            caption : 'test caption',
                            ratings : [{ _id   : 'test' + (i % 3),
                                        rating : 5 }] });
    testPhoto.save(function(err){
      if (--saves === 0) {
        done();
      }
    });
  }
}
Solution courtesy of: JohnnyHK

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.