将mongodb集合数据导出到Node JS中的CSV文件

Dia*_*kar 5 mongodb node.js

我在mongolab中创建了一个mongodb集合,并希望打印该collectionon中的所有文档。我有mongolab,要连接到集合的mongolab的网址是-

mongodb:// user:1234@ds041248.mongolab.com:41248 / new

示例文档结构为-

{
    "_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"
}
Run Code Online (Sandbox Code Playgroud)

我想将其打印,并将所有嵌套属性显示在列中。但我无法这样做,请帮助。

谢谢(提前),迪亚

aab*_*kar 6

在nodejs上实现json2csv库将数据导出到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);
        }
    })
Run Code Online (Sandbox Code Playgroud)


Hir*_* S. 5

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

nested选项值设置为true

并且还指定要从JSON获得的字段。对于嵌套文档,您可以这样指定details.Gender