I'm using a route to create a PDF using PDFKit. I would like to create a PDF that lists all posts
that belong to the current calendar
.
This code returns "undefined" for currentPosts.postDate
. However, if I do something like currentCalendar.name
, it returns the calendar
name without issue.
Where did I go wrong?
Router.route('/calendars/:_id/getPDF', function() {
var currentCalendar = Calendars.findOne(this.params._id);
var currentPosts = Posts.find({}, {fields: {calendarId: this.params._id}});
var doc = new PDFDocument({size: 'A4', margin: 50});
doc.fontSize(12);
doc.text(currentPosts.postDate, 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 can't test this, but this caught my eye:
var currentPosts = Posts.find({}, {fields: {calendarId: this.params._id}});
Posts.find({})
will return a whole recordset. But then you reference currentPosts.postDate
as if it's one item. Maybe try this:
var currentPost = Post.findOne({_id: this.params._id}, {fields: {postDate: 1}});
[...]
doc.text(currentPost.postDate, 10, 30, {align: 'center', width: 200});
If you wanted to get all the post dates, you'd have to loop through the results:
// .fetch() turns a mongo cursor into an array of objects
var currentPosts = Posts.find({calendarId: this.params._id}).fetch();
// Assuming you're using underscore.js
_.each(currentPosts, function (o) {
// do something with o.postDate
});