Publishing documents to an alternative collection name?

As you probably know having differerent publications of the same collection with different set of fields can create some problems on the application.

For instance on my NavBar i have a “counter” of “unread notifications” and on my “notifications page” i have a list of the notifications where all data is displayed.

Because the counter only need to subscribe to the “_id” and “unread” fields while the notifications page needs all the fields things can get mixed up and the notifications page will get some documents with missing fields.

One solution for that problem is to publish the documents under a different colletion name, for instance “NotificationsUnread” and “Notifications” as outlined on this article: http://braindump.io/meteor/2014/09/20/publishing-to-an-alternative-clientside-collection-in-meteor.html

My question is: is there a straight forward way to do that “natively” on meteor without depending on the “PublishComposite” package?

I found this other option: http://sunkay.github.io/meteor/2015/03/09/meteor-collection-subsets/ but i’m not sure if that’s the most up to date way of doing it considering meteor have had loads of updates after those articles were written?

I wouldn’t expect publish composite to help you here, you can publish pretty much whatever you want by using the publish API from within a publication https://docs.meteor.com/api/pubsub.html#Subscription-added. However this may be overkill in your case. In your NavBar do you also filter on unread? If you do there shouldn’t be a problem

1 Like

on the navbar i only subscribe to “unread and _id” fields, while on the “notifications” page i subscribe to the whole document.

hence why i would like to have two different subscriptions so i would avoid downloading extra notification information on the user device unless he decides to read them.

Right, so you subscribe to the same collection twice, you don’t need a different name:

Meteor.publish('unreadNotifications', function() {
  return Notifications.find({ unread: true }, { fields: { _id: 1, unread: 1 } })
});
Meteor.publish('allNotifications', function() {
  return Notifications.find({}, {})
});

You could also do this in one publication, with passing in an argument.

1 Like

The main caveat for this approach is the Minimongo will only merge on top-level fields, so if you’re fetching subsets of nested documents you will have issues.

Sounds like this doesn’t apply in your case, so the merging should work fine

1 Like

that’s exactly the problem on my case! but i did not go into many details in order to keep my question simple…

maybe i should have added that information too, my bad!

1 Like