【发布时间】:2015-08-17 06:07:16
【问题描述】:
我想下载从数据库 (nodeDB) 生成的 CSV 文件,其中包含以下条目。
这些条目应仅用作标题。
{
"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 文件已下载,但为空白。发生了什么事?
【问题讨论】:
-
你有格式问题,你真的写
dataCursor.length吗? -
是的,有什么问题,请解释一下
-
如果您尝试获取所有数据(例如
meteor shell中的console.log(nodeDB.find().fetch());),是否有任何数据? -
是的......这也是问题中显示的......
-
@garmina 您是否反对使用为您完成大部分工作的软件包?