Export the data from a Mongo DB database in a CSV

2.6k Views Asked by At

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>
1

There are 1 best solutions below

7
On BEST ANSWER

You can achieve all these things in your single file app.js file. We need to have json2csv module because this module has the parser class so that we can use parse() method to get the CSV format data as String. Here lean options tell mongoose to skip instantiating a full Mongoose document and just give you the Plain Old JavaScript Object POJO. And also I have used username and password as documents so change it accordingly.

const path = require('path');
const ejs = require('ejs');
const fs = require('fs');
const express = require('express');
//You need to have some documents into your DB first 
const Collection = require('your/Modal Path');
const Json2csvParser = require("json2csv").Parser;
const app = express();
const port = process.env.PORT || 3000;

//Templating Engine Ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

//Middleware
app.use(express.urlencoded({
    extended: true
}));
app.use(express.json());

//MONGO DB CONNECTION 
const url = 'mongodb://localhost:27017/users';
mongoose.connect(url, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    .then(() => {
        console.log('Successfully Established Connection with MongoDB')
    }).catch(err => {
        console.log('Failed to Establish Connection with MongoDB with Error: ' + err);
        process.exit();
    });

app.get('/export/csv', async (req, res) => {
    await Collection.find({}).lean().exec((err, data) => {
        if (err) throw err;
        const csvFields = ['_id', 'username', 'password']
        console.log(csvFields);
        const json2csvParser = new Json2csvParser({
            csvFields
        });
        const csvData = json2csvParser.parse(data);
        fs.writeFile("bezkoder_mongodb_fs.csv", csvData, function(error) {
            if (error) throw error;
            console.log("Write to bezkoder_mongodb_fs.csv successfully!");
        });
        res.send('File downloaded Successfully')
    });
});

//HOME route
app.get('/', (req, res) => {
    res.render('home.ejs');
});

//listening to the PORT Number 
app.listen(port, console.log(`Server is running at ${port}`));

So, this is how your app.js file will look like. And also create a home.ejs file inside views directory like views/home.ejs. and add the below code:

<form action="/export/csv" mehotd="GET">
    <button id="export-csv">Export CSV</button>
</form>