问题
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