Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 927
jseiller Avatar asked Jan 28 '26 03:01

jseiller


2 Answers

Using a method probably makes more sense if the data is not going to be changed very often. The publish/subscribe pattern is also possible here but instead of returning a cursor or anything, you will need to use the publication "gears" manually, like this:

Meteor.publish("myCustomPublication", function () {
  // here comes some custom logic
  this.added("myCollection", someUniqueId, someCustomData);
  this.ready(); // without this waitOn will not work
});
like image 152
Tomasz Lenarcik Avatar answered Jan 30 '26 19:01

Tomasz Lenarcik


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

like image 23
Kyll Avatar answered Jan 30 '26 18:01

Kyll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!