Posts not subscribing to single post page


#1

On my apps homepage all the posts show up, and the collection Posts.find().count() is accurate. But when I go to the individual post page Posts.find().count() gives me 0. I’m pretty sure it has to do with my routing and subscription through the routing. What exactly is going on?

Here is my routing code

Router.route('/:postsLimit?', {
    name: 'postsList',
    waitOn: function() {
    var limit = parseInt(this.params.postsLimit) || 5; 
    return Meteor.subscribe('posts', {sort: {submitted: -1}, limit: limit});
},
data: function() {
var limit = parseInt(this.params.postsLimit) || 5; 
 Session.set('pageView','list');
return {
  posts: Posts.find({}, {sort: {submitted: -1}, limit: limit})
};
}
});

Router.map(function() {
    this.route('singlePost',{
    path:'profile/:userName/post/:_id',
    waitOn: function() {
      return Meteor.subscribe('comments', this.params._id);},
    data:function(){
      Session.set('pageView','single');
      return Posts.findOne(this.params._id);}
  });
  this.route('editPost',{
    path:'/:userName/post/:_id/edit',
    data:function(){
      Session.set('pageView','single');
      return Posts.findOne(this.params._id);
    }
  });
  this.route('profile',{
   path:'profile/:userName',
    data:function(){
     return Profiles.findOne({userName: this.params.userName});
   }
  });

});

#2

The problem is placed in this route

Your subscribtion lives only for this route (everything that you defined inside waitOn). When your navigate to singlePost, previous route clear all its data and subscribtions so you get a clear collection!


#3

How do I add two subscriptions on a waitOn part of my code? I’m already waiting on the comments. Is there way to subscribe to comments and posts in the waitOn part of my code?

this.route('singlePost',{
    path:'profile/:userName/:_id',
    waitOn: function() {
      return Meteor.subscribe('comments', this.params._id);},
    data:function(){
      Session.set('pageView','single');
      return Posts.findOne(this.params._id);
    }
  });

#4

You can return an array of subscriptions like:

return [
  Meteor.subscribe('comments', this.params._id),
  Meteor.subscribe('foo', this.bar._id),
];

For what it’s worth I would recommend calling your subscription in your template instead of the router. There be dragons. Any time a reactive variable changes the router will re-run which can cause all kinds of problems down the road.

Also instead of waitOn, using a loading spinner usually feels faster to the user.

Check out this:
https://www.discovermeteor.com/blog/template-level-subscriptions/


#5

I’ll check it out.

It’s interesting you mentioned discover meteor, that’s the tutorial book of theirs i’m following. My code is exactly like this commit of theirs. I must be missing something…