【问题标题】:How to convert json stored in DB into csv using meteor如何使用流星将存储在数据库中的 json 转换为 csv
【发布时间】: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 您是否反对使用为您完成大部分工作的软件包?

标签: csv meteor


【解决方案1】:

首先,假设您的nodeDB 工作正常。你的问题可能是/csv没有定义路由,所以试试下面的测试。

<template name="templateForCSV">
    <a href="/csv" target="_blank">Download the CSV</a>
</template>

如果还是空白,我猜你的nodeDB 是空白的,所以试试下面的测试。

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 文件。请注意,我将上面的语法稍微更改为我使用的语法。

试试这个,让我们知道它是否有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 2018-05-24
    相关资源
    最近更新 更多