Search code examples
meteoriron-router

Meteor : how to publish custom JSON data?


Edit: The solution I used is @Kyll's one.

Suppose the server side objects I'd like to return are "complicated" to build and need different attributes from different collections.

I first tried:
/server/publications.js

Meteor.publish('myCustomDocument', function(){
    // suppose here that I need to X.find() different collections
    // and create a complex Array of JSON data (which contains different
    // attributes from different Collections
    return [
            {appName: 'aName',
             category: 'catName',
             anotherField: 'something'},
            (...)
        ];
});

It doesn't work because it's not returning a cursor. What I want to do is to create a document (or an array of documents) which is built from different collections.
I do not need to observe the changes on that document.

I have created a collection for it :

/collections/myCollection.js

MyCollection = new Meteor.Collection('myCollection');

On the client side, using iron-router, what I tried to do is:

/lib/router.js

this.route('myPage',{
    path: '/myPage',
    waitOn: function(){ return Meteor.subscribe('myCollection'); },
    data: function(){ return MyCollection.find(); }
});

How would I achieve the sending of non-reactive data to the client?


Solution

  • Meteor Pubs/Subs are made for data reactivity. If you don't need reactivity but some one-shot data the server computes for you and sends back, you need a method!

    // Server code
    Meteor.methods('getComplexData', function() {
      var complexData = { /* make your complex data */ };
      return complexData;
    });
    
    // Client code
    Meteor.call('getComplexData', function(err, data) {
      if(err) {
        // Handle error
      }
      else {
        Session.set('complexData', data);
      }
    });
    

    More about Session