Reputation: 3869
I have a collection called "Articles". Each article has a category. I would like to have a global variable being an array with each distinct category value in my Articles collection.
I tried to do it this way:
/models/article.coffee:
@Articles = new Meteor.Collection "articles"
Articles.categories = ->
Meteor.call "articleCategories", (e, r) ->
unless e
return r
/server/article_server.coffee:
Meteor.methods
articleCategories: ->
categories = _.uniq(Articles.find({}, {sort: {category: 1}, fields:
{category: true}}).fetch().map (x) ->
x.category
, true)
return categories
This doesn't work. The result is "undefined" when I call Articles.categories() from the console.
What am I doing wrong?
EDIT:
I want to do this because I want my article categories to be available everywhere in the website.
As Articles collection will not be published on every pages, I tought, I could just generate an array server side and pass it over to the client.
But maybe it's not a good idea...
Upvotes: 2
Views: 143
Reputation: 22696
A Meteor.method
will always return undefined on the client (unless a simulation/stub exists and it's called within another parent method) so this behavior is expected.
I'm not sure why you'd need a Meteor.method
in this particular use case though, can't you just copy your method code inside your class method ?
EDIT :
To accomplish what you want to do, I'd suggest changing your model to create a Categories
collection filled with every possible categories and just publish the entire content to the client.
Then just use a foreign key in your Articles
collection.
An added benefit will be that your categories access client side will be reactive, contrary to using a Meteor.method
.
Whether it's Telescope or even Wordpress I think this schema is very popular.
Upvotes: 1
Reputation: 160
Take a look at this package:
https://github.com/dburles/meteor-collection-helpers
And add something like this (I wrote in javascript) in your model:
Articles.helpers({
categories: function(){
return _.uniq(
_.pluck(Articles.find({}, {sort: {category: 1}, fields:
{category: true}}).fetch(), 'category'),
true
);
}
});
Upvotes: 0