2

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

ndemoreau
  • 3,849
  • 4
  • 43
  • 55

2 Answers2

1

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.

Community
  • 1
  • 1
saimeunt
  • 22,666
  • 2
  • 56
  • 61
  • I'm suggesting a model schema shift in my latest edit. – saimeunt May 19 '15 at 02:37
  • This is true but it is more maintenance. I ended up creating helpers at template levels (which I need to do anyway). They are reactive. I hoped there was another way of publishing different views of a same collection from the server. – ndemoreau May 19 '15 at 04:39
0

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
        );
    }
});
  • As far as I know, collection-helpers work at instance level, not at collection level. So this doesn't work for me. Please note that I edited the question to make my goal more clear. – ndemoreau May 19 '15 at 02:29