Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving multiple documents with Mongoose and doing something when last one is saved

I want to save 8 objects to a MongoDB database using Mongoose. When the last document is saved, I want to report (i.e. send an event) that all documents have been saved.

The way I'm doing it now is quite messy (especially for increasingly larger amounts of documents I want to save).

This is how I have it now (just for 4 people for this example). Is there a cleaner way you can recommend?

person1.save(function(err, result){
    if (err) console.log(err);
    else{
        person2.save(function(err, result){
            if (err) console.log(err);
            else{
                person3.save(function(err, result){
                    if (err) console.log(err);
                    else{
                        person4.save(function(err, result){
                            if (err) console.log(err);
                            else{
                                done();
                            }
                        });
                    }
                });
            }
        });
    }
});
like image 1000
CodyBugstein Avatar asked Jul 10 '15 20:07

CodyBugstein


2 Answers

A useful library to coordinate asynchronous operations is async. In your case, the code would look something like this:

var people = [ person1, person2, person3, person4, ... ];

async.eachSeries(people, function(person, asyncdone) {
  person.save(asyncdone);
}, function(err) {
  if (err) return console.log(err);
  done(); // or `done(err)` if you want the pass the error up
});
like image 194
robertklep Avatar answered Oct 19 '22 09:10

robertklep


Using promises and Array.map()

const userPromises = persons.map(user => {
  return new Promise((resolve, reject) => {
    person.save((error, result) => {
      if (error) {
        reject(error)
      }
      resolve(result);
    })
  })
});

Promise.all(userPromises).then((results) => {
  //yay!
  //results = [first, second, etc...]
}, (error) => {
  //nay!
})
like image 44
primavera133 Avatar answered Oct 19 '22 10:10

primavera133