I have a project in Node JS in which I want to export the data contained in the database in Mongo DB in a CSV file through a button in the view (index.ejs).
I am using mongoose for the connection to the database and to export the data to the CSV I am trying to use json-2-csv.
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.
This is my app.js:
const fs = require('fs');
const json2csv = require("json2csv").Parser;
const userModel = require('./models/users');
const express = require("express");
const app = express();
app.get('/export/csv', async (req, res) => {
await userModel.find((err, data) => {
if (err) throw err;
const json2csvParser = new json2csv({ header: true });
const csvData = json2csvParser.parse(data);
fs.writeFile("users.csv", csvData, function(error) {
if (error) throw error;
console.log("Write to bezkoder_mongodb_fs.csv successfully!");
});
});
});
This is the button:
<form action="/export/csv" mehotd="GET">
<button id="export-csv">Export CSV</button>
</form>
You can achieve all these things in your single file
app.jsfile. We need to havejson2csvmodule because thismodulehas theparserclass so that we can useparse()method to get theCSVformat data asString. Hereleanoptions tell mongoose to skip instantiating a fullMongoose documentand just give you thePlain Old JavaScript ObjectPOJO. And also I have usedusernameandpasswordasdocumentsso change it accordingly.So, this is how your
app.jsfile will look like. And also create ahome.ejsfile insideviews directorylikeviews/home.ejs. and add the below code: