0

So i am trying to run multiple queries, all while creating rows to an excel sheet, and then after all that actually writing to an excel file The problem I keep stumbling over is that I end up writing to the excel file before I am done with my queries and the rows have been created. Here is the my code:

var writeRows = function(){ 
// setting up of excel file
Child.find(function(err,children){
        children.forEach(function(item, index){
          User.findOne({_id: item.get_gaurdian()}, function(err, parent){
            console.log(item.firstname);
            sheet.addRow({
              firstname: item.firstname,
              lastname: item.lastname,
              birthday: item.birthday,
              address: item.address,
              parent_name: parent.full_name(),
              // more fields...
            });
          });
        });

  });
}

And then in my controller i call:

writeRows().then(function(){
d = new Date().toDateString().split(' ').join('_');
filename = './public/spreadsheets/registration_1'+d+'.xlsx';
workbook.xlsx.writeFile(filename)
  .then(function() {
    console.log("wrote to a file");
    res.send('finished');
  });
});

How can i wait for the queries to be done and rows to be added, before actually writing to the file?

tyler16
  • 73
  • 6

0 Answers0