Meteor:如何发布自定义 JSON 数据?

Meteor : how to publish custom JSON data?

编辑:我使用的解决方案是@Kyll 的解决方案。

假设我想 return 构建的服务器端对象 "complicated" 需要来自不同集合的不同属性。

我第一次尝试:
/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'},
            (...)
        ];
});

它不起作用,因为它不是 return 游标。我想要做的是创建一个由不同集合构建的文档(或文档数组)。
我不需要观察那个文档的变化。

我已经为它创建了一个集合:

/collections/myCollection.js

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

在客户端,使用iron-router,我尝试做的是:

/lib/router.js

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

如何实现向客户端发送非反应性数据?

流星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

如果数据不会经常更改,则使用方法可能更有意义。 publish/subscribe 模式在这里也是可能的,但不是返回光标或任何东西,您需要手动使用发布 "gears",如下所示:

Meteor.publish("myCustomPublication", function () {
  // here comes some custom logic
  this.added("myCollection", someUniqueId, someCustomData);
  this.ready(); // without this waitOn will not work
});