0

我在 Node JS 中有一个项目,我想Mongo DB通过视图中的按钮 ( ) 将数据库中包含的数据导出到 CSV 文件中index.ejs。我mongoose用于连接到数据库并将数据导出到我尝试使用的 CSV json-2-csv

在按钮中,我添加了一个 url,以便能够通过按钮调用该 url,并且 json-2-csv 函数响应该 url,但我不知道该怎么做,或者它是否是最好的方法。

这是我的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!");
      });
      
  });
});

这是button

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

1 回答 1

0

您可以在单个文件app.js文件中实现所有这些事情。我们需要有json2csv模块,因为它moduleparser类,这样我们就可以使用parse()方法来获取CSV格式数据为String. 这里lean的选项告诉猫鼬跳过实例化一个完整的Mongoose document,只给你Plain Old JavaScript Object POJO. 而且我也使用过username并相应passworddocuments更改它。

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>
于 2021-05-30T09:50:47.663 回答