Help with helper classes


#1

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?


#2

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


#3

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}}


#4

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.

#5

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


#6

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>