简体   繁体   中英

Allowing a Route to Access Data from a Collection with Meteor

I'm using a route to create a PDF using meteor-pdfkit. Here is my current code which allows me to display my Calendars ID onto the PDF.

 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'});

However, when I try to include other information from the Calendars collection, the data comes back as undefined or creates an error. For example, if I try to call 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'});

I'm assuming this is because the route doesn't have access to the information from the collection. How do I allow the route to access the information from the Calendars collection?

In your code, currentCalendar is being set to an id. I think you want to write:

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

Now currentCalendar will be a document with properties, eg currentCalendar.name .

currentCalendar.name is undefined because you are looking for a property name on the string currentCalendar which is nothing more than the id value supplied in the URL. Therefore, all it knows is a number.

What you would have to do is create some array with information about your calendars, ie:

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

Then, in your route, you can then get the information based on the index as such:

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

Because now calendars[currentCalendar].name is defined

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM