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

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


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});


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!})


I would recommend to have an array and save with iteration. Will have same performance but code would be cleaner.

You can have

var Person = mongoose.model('Person');var people = [];people[0] = new Person({id: 'someid'});people[0].set('name', 'Mario');people[1] = new Person({id: 'someid'});people[1].set('name', 'Mario');people[2] = new Person({id: 'someid'});people[2].set('name', 'Mario');var errors = [];for(person in people){ people[person].save(function(err, done){  if(err) errors.push(err);  if (person === people.length){ yourCallbackFunction(errors){    if (errors.length!=0) console.log(errors);    //yourcode here   };  } });}