title: Mongoose stream data and export data to CSV file
body: <p>I'm trying to export a CSV file with following codes but its not working. I'm assuming that my data will be huge, hence Mongoose cursor will be the option. I also notice that I had mention 'batchSize' of 500 still it spitting 1 at a time.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>module.exports.export2CSV = (req, res)=&gt;{
    var limit       = 250000;
    var filename    = 'export.csv';
    var query       = User.find();
    if (limit){query.limit(limit);} 
    var headers = {
        'Content-Type': 'text/csv',
        'Content-disposition': 'attachment;filename=' + filename
    }
    // res.writeHead(200, headers)
    res.setHeader('Content-disposition', 'attachment; filename='+filename);
    res.set('Content-Type', 'text/csv');
  
  
    var stream = User.aggregate().cursor({ batchSize: 500 }).exec().stream();
    stream.on('data', function (doc) {
      // do whatever you want with the data
    res.write(doc);
  }).on('error', function (err) {
    // handle errors
    res.end();
  }).on('end', function () {
    // close files
    res.end();
  });
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>Right now I'm calling this code directly but later I will be calling it from a Ajax request.</p>
  
  <p>Please suggest the best and fastest way of doing it.</p>