generate csv from mongo response and save to file system nodejs code example
Example: export mongo to csv node
const json2csv = require('json2csv').parse;
const dateTime = new Date().toISOString().slice(-24).replace(/\D/g,
'').slice(0, 14);
const filePath = path.join(__dirname, "../../../", "public", "exports", "csv-" + dateTime + ".csv");
let csv;
const student = await req.db.collection('Student').find({}).toArray();
const fields = ['id','name','country'];
try {
csv = json2csv(booking_info, {fields});
} catch (err) {
return res.status(500).json({err});
}
fs.writeFile(filePath, csv, function (err) {
if (err) {
return res.json(err).status(500);
}
else {
setTimeout(function () {
fs.unlink(filePath, function (err) {
if (err) {
console.error(err);
}
console.log('File has been Deleted');
});
}, 30000);
res.download(filePath);
}
})