您可以在单个文件app.js
文件中实现所有这些事情。我们需要有json2csv
模块,因为它module
有parser
类,这样我们就可以使用parse()
方法来获取CSV
格式数据为String
. 这里lean
的选项告诉猫鼬跳过实例化一个完整的Mongoose document
,只给你Plain Old JavaScript Object
POJO
. 而且我也使用过username
并相应password
地documents
更改它。
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}`));
所以,这就是你的app.js
文件的样子。并且还在里面创建一个home.ejs
文件,views directory
比如views/home.ejs
. 并添加以下代码:
<form action="/export/csv" mehotd="GET">
<button id="export-csv">Export CSV</button>
</form>