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.js
file. We need to havejson2csv
module because thismodule
has theparser
class so that we can useparse()
method to get theCSV
format data asString
. Herelean
options tell mongoose to skip instantiating a fullMongoose document
and just give you thePlain Old JavaScript Object
POJO
. And also I have usedusername
andpassword
asdocuments
so change it accordingly.So, this is how your
app.js
file will look like. And also create ahome.ejs
file insideviews directory
likeviews/home.ejs
. and add the below code: