1

I am looping over a collection of Users in node using mongoose. I want to save the data of every User in a excel File.

    Usr.findById(usrID, function(err, foundTagestipp){
        sheet1.set(1, counter, 'some Userdata');
    }

The problem is that I want to save the file after it went through the whole collection.

So when do I know when the last user is done? Can I somehow give that to a callback or can I somehow get information from mongoose when it is done?

I hope it is clear what I meant by that... Sorry for the nooby question

Paul
  • 154
  • 3
  • 12
  • Possible duplicate of [How to export collection to CSV in MongoDB?](https://stackoverflow.com/questions/6814151/how-to-export-collection-to-csv-in-mongodb) – str Oct 16 '17 at 13:18

1 Answers1

1

you can wrap each async call inside a promise, collect a list of promises and resolve them outside the loop with a call to Promise.all() then execute your business logic.

let promises = [];
myCollection.forEach(elem => {
 let promise = new Promise( (resolve, reject) => {
   Usr.findById(elem.usrID, function(err, foundTagestipp){
      if(err) {
        return reject(err);
      }
      resolve({userId: elem.usrId, userData: foundTagestipp})
    }
 })
 promises.push(promise);
})

Promise.all(promises)
.then(data => {
   //here all the findById have already been called
   //you can save your data to the csv 
 })
Karim
  • 8,454
  • 3
  • 25
  • 33