title: NodeJs Download Mongoose document as a file
body: <p>I'm trying to trigger a file download from a mongoose document lookup however, I can't seem to return the returned data as a file.</p>
  
  <p>As you can see i'm transforming some json data returned from the DB into a CSV, and then trying to send it to the client as a file type text/csv.</p>
  
  <p>The data doesn't seem to be generate a file attachment when the response is sent. </p>
  
  <p>Any suggestions or pointers in the right direction would be appreciated.</p>
  
  <pre><code>exports.download = function (req, res, next) {
    var dataSetId = req.params.id;
  
    DataContentModel.findById(dataSetId, function (err, doc) {
      if (err) return next(err);
      if (!doc) return res.send({'error': 'This record was not found.'});
  
      var keys = [];
      for(var k in doc.data[0]) keys.push(k);
  
      json2csv({data: doc.data, fields: keys}, function (err, csv) {
        if (err) console.log(err);
  
        res.setHeader('Content-Type', 'text/csv');
        res.setHeader('Content-Disposition', 'attachment; filename=csv.csv');
        res.send(csv);
  
      });
    });
  
  };
  </code></pre>