Reputation: 7162
I am trying to run the query shown below through a server method, unfortunately the data inside the array returned by this query is not displayed in my template, what am I missing / doing wrong here?
/server/methods.js
Meteor.methods({
'getCategoriesEx': function () {
return Categories.find({children: {$size: 0}},{sort: {name: 1}}).fetch();
}
});
/client/categories.js
Template.Categories.rendered = function() {
};
Template.Categories.helpers({
categories: function() {
Meteor.call('getCategoriesEx', function(error, list){
if(error)
return alert(error.reason);
return list;
});
}
})
/client/categories.html
<div class="col_half">
<label for="categories"> categories </label>
<select id="categories" name="categories" class="sm-form-control">
<option value="">-- Select One --</option>
{{#each categories}}
<option value="{{_id}}">{{name}}</option>
{{/each}}
</select>
</div>
Data returned by the query:
[Object, Object, Object, Object]
0: Object
_id: "Pwmd9wFTf8zs8nbWn"children: Array[0]title: "A1"__proto__: Object
1: Object
2: Object
3: Object
Upvotes: 0
Views: 1155
Reputation: 15442
Chris's answer is the standard way to do things, however you've specifically stated that you're trying to use a method so I assume there's a reason for that.
The problem is that your helper is returning nothing at the point that it's called (it called the method and returns immediately). At the point that your callback is called back there's nothing to return the data to.
One solution would be to update a reactive variable instead. For example, using the Sessions object.
Also note that helpers can be called frequently. You probably don't really want to be calling the server method each time an helper is called. A better place to put that would be the rendered code. So (untested):
Template.Categories.rendered = function() {
Meteor.call('getCategoriesEx', function(error, list){
if(error)
alert(error.reason);
Session.set('categories', list);
});
}
Template.Categories.helpers({
categoriesResult: function() {
return Session.get('categories')
})
and
<div class="col_half">
<label for="categories"> categories </label>
<select id="categories" name="categories" class="sm-form-control">
<option value="">-- Select One --</option>
{{#each categoriesList}}
<option value="{{_id}}">{{name}}</option>
{{/each}}
</select>
</div>
Upvotes: 0
Reputation: 1754
You are not using a reactive data source in your helper. Restructure it to use client side reactive mini mongo queries by publishing your data.
So something like this: Server:
Meteor.publish("categories", function() { return Categories.find(); }
Client:
Template.Categories.created = function() {
Meteor.subscribe("categories");
};
Template.Categories.helpers({
categories: function() {
return Categories.find({children: {$size: 0}},{sort: {name: 1}});
}
})
Upvotes: 1