title: Export the data from a Mongo DB database in a CSV
body: <p>I have a project in Node JS in which I want to export the data contained in the database in <code>Mongo DB</code> in a CSV file through a button in the view (<code>index.ejs</code>).
  I am using <code>mongoose</code> for the connection to the database and to export the data to the CSV I am trying to use <code>json-2-csv</code>.</p>
  <p>In the button I have added a url to be able to call that url through the button and that the json-2-csv function responds to that url but I don't know how to do it or if it is the best way.</p>
  <p>This is my <code>app.js</code>:</p>
  <pre><code>const fs = require('fs');
  const json2csv = require(&quot;json2csv&quot;).Parser;
  const userModel = require('./models/users');
  const express = require(&quot;express&quot;);
  const app = express();
  
  app.get('/export/csv', async (req, res) =&gt; {
    await userModel.find((err, data) =&gt; {
        if (err) throw err;
        const json2csvParser = new json2csv({ header: true });
        const csvData = json2csvParser.parse(data);
        fs.writeFile(&quot;users.csv&quot;, csvData, function(error) {
            if (error) throw error;
            console.log(&quot;Write to bezkoder_mongodb_fs.csv successfully!&quot;);
        });
        
    });
  });
  </code></pre>
  <p>This is the <code>button</code>:</p>
  <pre><code>&lt;form action=&quot;/export/csv&quot; mehotd=&quot;GET&quot;&gt;
      &lt;button id=&quot;export-csv&quot;&gt;Export CSV&lt;/button&gt;
  &lt;/form&gt;
  </code></pre>