Meteor : how to publish custom JSON data?

时光总嘲笑我的痴心妄想 提交于 2019-12-30 07:11:30

问题


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?


回答1:


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




回答2:


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
});


来源:https://stackoverflow.com/questions/28812306/meteor-how-to-publish-custom-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!