Help with helper classes

I am building a custom forum solution for my website and I want to populate the “Last Post by {{lastComment}}”. I can’t seem to access the user who commented last on the specific post. Can anyone help me out?

Template.postItem.helpers({
lastComment: function() {
		return Comments.find({userId: this._id}), ({sort: {submitted: -1}});
	}
});
<template name="postItem">
        <a href="{{pathFor 'postPage'}}"></a>
        <tbody id="thread">
      <td id="postBy" style="text-align:center">{{lastComment}}</td>
        </tbody>
</template>

All I get returned is “[object Object]”.

What am I doing wrong?

Your helper is returning a cursor (Collection.find). What you want is to return a document (Collection.findOne)

Hi! In your code you get a Collection.Cursor.
It store array of objects.
Now you need to call value of object in you array.
Use {{#each}} block, and you will get access to object data.

{{#each lastComment}} {{content]} //for example {{/each}}

How’s this look?

lastComment: function() {
		return Comments.findOne({}, { fields: { "author": 1
  	}, sort: { "submitted": -1 }
		});

I am getting the error:

Error: {{#each}} currently only accepts arrays, cursors or falsey values.

The problem is your “findOne” query type, you need to use Comments.find(). It will return cursor of array.

Use this:
Comments.find({}, { fields: { "author": 1}, sort: { "submitted": -1 }});

1 Like

Owhhh now i understood. Sorry.
If you need one object, use findOne(), if array - find().
I thought you need array:)

Template.postItem.helpers({
lastComment: function() {
		return Comments.findOne({userId: this._id}), ({sort: {submitted: -1}});
	}
});

In template:

<template name="postItem">
        <a href="{{pathFor 'postPage'}}"></a>
        <tbody id="thread">
      <td id="postBy" style="text-align:center">{{lastComment.fieldYouNeed}}</td>
        </tbody>
</template>