I am listing all notifications belonging to an user with
this.route('notifications', {
path: '/notifications',
template: 'notificationList',
waitOn: function() {
return Meteor.subscribe('notifications');
},
data: function() {
return Notifications.find(
{userId: Meteor.userId()},
{sort: {createdAt: -1}}
);
},
fastRender: true
});
I am publishing the docs with
Meteor.publish("notifications", function () {
return Notifications.find(
{userId: this.userId},
{sort: {createdAt: -1}}
);
});
I am confused about what to do where. Do I have to filter for user id in both Meteor.publish()
AND data: ...
? Do I have to sort in both functions? I have seen that it is also possible to sort and filter in Meteor.subscribe()
.
It seems a bit redundant to do almost the same in all three functions. Am I doing it correctly?
When calling Meteor.publish it's usually necessary to sort so that the correct documents are sent when there's a limit being applied. For example, if you're only asking for 10 items then you'll need to sort them first to ensure that you have the right 10 items rather than 10 random results.
The client's sort order doesn't have any relation to that of the server's publish request, and there's no guarantee that they'll be the same. Consider for example the case where there are multiple publish requests posting to the same collection on the client, each with a different sort order. It would be impossible to have these results pre-sorted in a useful way.
Therefore, you usually also need to request that the items be sorted when accessing the collection on the client. The sort doesn't have to be the same as that on the server (although it often is).
As for Meteor.subscribe, the parameters you pass there depend on your publish function's parameters, so you can have your client pass the sort order to the publish function. This is useful when you need to have the same publish function return different results based on the sort order. Furthermore if the code for subscribing and supplying the data context are in the same route controller then you can have a single variable hold the sort condition and therefore reduce code duplication and potential for error.