How to Create CSV export from MongoDB JavaScript NodeJS

Example of creating a CSV file export from a mongo database table using the jsonexport and mongoose NPM packages. ` require('dotenv').load() const fs = require('fs') const uuid = require('uuid-base62') const mongoose = require('mongoose') const jsonexport = require('jsonexport') const Post = require('../../model/Post') const PostForm = require('../../model/PostForm') const FormSubmissions = require('../../model/FormSubmissions') const getFormSubmissions = async () => { let submissions = await FormSubmissions.find() .select('createdAt post form fields -_id') .populate('post') .populate('form') let data = [] submissions.map(sub => { let row = { createdAt: sub.createdAt, post: sub.post.id, form: sub.form.id } if (sub.fields) { sub.fields.map(field => rowfield.field = field.value) }

data.push(row) }) return data } const createCsvFile = (submissions) => { jsonexport(submissions,function(err, csv){ if(err) return console.log(err) let filename = ${uuid.uuid()}.csv

fs.writeFile(${filename}, csv, (err) => { if (err) throw err; console.log(${filename}); }) }) } (async () => { let db = process.env.NODE ENV === 'production' ? process.env.DB URI PROD : process.env.DB URI_DEV await mongoose.connect(db) let submissions = await getFormSubmissions() await mongoose.connection.close() createCsvFile(submissions) })() `