将mongodb集合数据导出到节点js中的csv文件

时间:2015-08-31 09:08:39

标签: node.js mongodb

我在mongolab中创建了一个mongodb集合,并希望在该集合中打印所有文档。我有mongolab和mongolab的网址与集合有关 -

的mongodb://用户:1234@ds041248.mongolab.com:41248 /新

示例文档结构是 -

{
    "_id": "9759572745-Sing",

   "details": {
    "Gender": "M",
    "PreTrainingStatus": "Fresher",
    "Religion": "Hindu",
    "attendanceInPercentage": "",
    "batchHolders": {
        "AssessmentDate": "Thu Jul 16 2015",
        "CourseFee": "7500",
        "isEditable": false
    },
    "batchID": "282726",
    "eid": "",
    "whereDidYouHearAboutStar": "---Select---",
    "skillInstructorOrTrainerName": "282726",
    "specificGovtInstitutetieups": "---Select---",
    "isSelected": false,
    "isEditable": false
},
"addedOnMs": 1439455766000,
"submittedOnMs": 1439454813000,
"latitude": "27.409566879272",
"longitude": "77.69295501709",
"locationName": "Uttar Pradesh 281006,null"
}

我想打印它以及要在列中显示的所有嵌套属性。 但我无法这样做,请帮助。

谢谢(事先), Dia

2 个答案:

答案 0 :(得分:4)

您可以使用https://www.npmjs.com/package/json2csv

nested选项值设为true

并指定您想要的JSON字段。对于嵌套文档,您可以指定此details.Gender

答案 1 :(得分:0)

实现json2csv库以将数据导出到nodejs上的csv文件

示例

const json2csv = require('json2csv').parse;

//For unique file name
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();

// Logging student
// [{id:1,name:"John",country:"USA"},{id:1,name:"Ronny",country:"Germany"}]

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) { // delete this file after 30 seconds
                if (err) {
                    console.error(err);
                }
                console.log('File has been Deleted');
            });

        }, 30000);
            res.download(filePath);
        }
    })