【问题标题】:Allowing a Route to Access Data from a Collection with Meteor使用 Meteor 允许路由访问集合中的数据
【发布时间】:2015-09-22 09:37:16
【问题描述】:

我正在使用meteor-pdfkit 创建PDF 的路线。这是我当前的代码,它允许我在 PDF 上显示我的 Calendars ID

 Router.route('/calendars/:_id/getPDF', function() {
     var currentCalendar = this.params._id;
     var doc = new PDFDocument({size: 'A4', margin: 50});
     doc.fontSize(12);
     doc.text(currentCalendar, 10, 30, {align: 'center', width: 200});
     this.response.writeHead(200, {
         'Content-type': 'application/pdf',
         'Content-Disposition': "attachment; filename=test.pdf"
     });
     this.response.end( doc.outputSync() );
 }, {where: 'server'});

但是,当我尝试从 Calendars 集合中包含其他信息时,数据会以未定义的形式返回或产生错误。例如,如果我尝试拨打curentCalendar.name:

 Router.route('/calendars/:_id/getPDF', function() {
     var currentCalendar = this.params._id;
     var doc = new PDFDocument({size: 'A4', margin: 50});
     doc.fontSize(12);
     doc.text(currentCalendar.name, 10, 30, {align: 'center', width: 200});
     this.response.writeHead(200, {
         'Content-type': 'application/pdf',
         'Content-Disposition': "attachment; filename=test.pdf"
     });
     this.response.end( doc.outputSync() );
 }, {where: 'server'});

我假设这是因为路由无法访问集合中的信息。如何允许路由访问日历集合中的信息?

【问题讨论】:

    标签: javascript meteor routes pdfkit


    【解决方案1】:

    在您的代码中,currentCalendar 被设置为一个 id。我想你想写:

    var currentCalendar = Calendars.findOnw(this.params._id);
    

    现在currentCalendar 将是一个具有属性的文档,例如currentCalendar.name.

    【讨论】:

    • 如此简单。我喜欢它。谢谢大卫。
    【解决方案2】:

    currentCalendar.name 未定义,因为您正在字符串 currentCalendar 上查找属性 name,它只不过是 URL 中提供的 id 值。因此,它只知道一个数字。

    您需要做的是创建一些包含日历信息的数组,即:

    global.calendars = [{name: "Holidays", data: ...}, {name: "Tests", data: ...}]

    然后,在您的路线中,您可以根据索引获取信息,如下所示:

    doc.text(calendars[currentCalendar].name, 10, 30, {align: 'center', width: 200});

    因为现在calendars[currentCalendar].name 已定义

    【讨论】:

    • 我假设包含来自现有日历集合而不是静态数组的数据会相当容易?
    • @JeremyE David 的回答展示了如何从现有集合中做到这一点。
    • 谢谢卡尔!感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2012-04-14
    • 2018-09-09
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多