如何使用流星将存储在数据库中的json转换为csv [英] How to convert json stored in DB into csv using meteor
问题描述
我想下载从数据库(nodeDB)生成的CSV文件,该文件具有以下条目。
这些条目应仅用作标题。
I want to download a CSV file generated from a database (nodeDB) which has the following entries.
These entries should act as headers only.
{
"META": {
"TEMPLATE_NAME": "B",
"TEMPLATE_GROUP": "Product",
"KEYWORDS": [
"cc"
],
"TEMPLATE_SUBGROUP": ""
},
"VARIENTS": [
{
"NAME": "Brand",
"DATATYPE": "Text",
}
]
}
我写了以下代码:
HTML:
<template name="templateForCSV">
<a href="{{pathFor 'csv'}}" target="_blank">Download the CSV</a>
</template>
JS:
if (Meteor.isServer) {
Meteor.startup(function () {
//CSV Download
var DataCursor=nodeDB.find({});
if (DataCursor.count() === 0) {
for(var i=1; i<=DataCursor.length; i++) {
//Example for Now, has to be changed
nodeDB.insert({Brand: "Brand" + i,Price: "Price" + i, Description:"Description" + i});
}
}
});
}
Router.route('/csv', {
where: 'server',
action: function () {
var filename = 'data.csv';
var fileData = "";
var headers = {
'Content-type': 'text/csv',
'Content-Disposition': "attachment; filename=" + filename
};
var records = nodeDB.find();
// This is the main problem. build a CSV string. Oversimplified. You'd have to escape quotes and commas.
records.forEach(function(rec) {
fileData += rec.META + "," + rec.VARIENTS + "," + "\r\n";
});
this.response.writeHead(200, headers);
return this.response.end(fileData);
}
});
CSV文件已下载,但为空白。
The CSV file is downloaded but it is blank. What's happening?
推荐答案
首先,假设您的 nodeDB
可以正常工作。您的问题可能是未为 / csv
定义路线,因此只需尝试以下测试即可。
First, assume that your nodeDB
works fine. Your problem could be that the route is not defined for /csv
, so just try the below to test.
<template name="templateForCSV">
<a href="/csv" target="_blank">Download the CSV</a>
</template>
如果仍然空白,我想您的 nodeDB
为空白,因此请尝试以下内容进行测试。
If that still turns up blank, I would guess that your nodeDB
is blank, so try the below to test.
Router.route('/csv', function () {
var filename = 'data.csv';
var fileData = "hello, world";
var headers = {
'Content-type': 'text/csv',
'Content-Disposition': "attachment; filename=" + filename
};
this.response.writeHead(200, headers);
this.response.end(fileData);
}, {where: "server"});
应下载带有 hello,world的CSV文件。请注意,我将上面的语法更改为所使用的语法。
The CSV file with "hello, world" should be downloaded. Note that I changed the syntax a bit on the above to what I use.
尝试一下,让我们知道它是否有效。
Try this and let us know if it works.
这篇关于如何使用流星将存储在数据库中的json转换为csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!