torchhound
torchhound

Reputation: 550

Publish/subscribe not loading in Blaze template

My code was working fine until I implemented publish/subscribe. I followed the basic tutorial and checked the source code and I'm not doing anything different. Everything builds and runs but nothing from MongoDB gets displayed in the Blaze template.

imports/api/features.js

if (Meteor.isServer) {
   Meteor.publish('features', function featuresPublication() {
      return Features.find({});
   });
   Meteor.publish('comments', function commentsPublication() {
      return Features.find({}, {fields: {comments: 0}});
   })
};

client/main.js

Template.body.onCreated(function bodyOnCreated() {
  Meteor.subscribe('features'); 
});

client/main.html

<body>
  <h1 id="title">Feature Requests</h1>
  {{#if currentUser}}
    <button class="ui green button create" id="create">Add a New     Feature Request</button>
    {{> requestForm}}
    {{#each features}}
      {{> feature}}
    {{/each}}
  {{else}}
    {{> loginButtons}}
  {{/if}}
</body>

Edit #1

Before I ran meteor remove autopublish my code looked like this and worked:

Template.body.helpers({ 
  features() {
    return Features.find({}, {sort: {createdAt: -1}});
  },
  comments() {
    return Features.find({}, {fields: {comments: 0}}); 
  },
});

Edit #2

Thanks to everyone who contributed an answer. I fundamentally misunderstood how publish/subscribe worked. I didn't realize I still needed to call return Features.find({}) after I subscribed. Here's my working code:

import { Features } from '../imports/api/features.js';

import '../imports/api/features.js'

Template.body.onCreated(function bodyOnCreated() {
  Meteor.subscribe('features'); 
});

Template.body.helpers({
  features: function() {
    return Features.find({});
  }
});

Upvotes: 0

Views: 119

Answers (3)

Sean
Sean

Reputation: 2729

I see you are using the imports directory. Have you remembered to import your publication file to the server/main.js file?

server/main:

import 'imports/path/to/publications.js'

Upvotes: 1

user105375
user105375

Reputation:

Disregard the first answer. The lack of an autorun is what first caught my attention but since you're not passing any args to subscribe it is not needed.

My next question would be: In client/main.html, where is the reference to features coming from? Is there a features helper on Template.body? If not, you'll need to add it:

Template.body.helpers({
  features: function() {
    return Features.find({});
  }
});

Also, see Meteor Subscribe & Publish with external api

Upvotes: 1

user105375
user105375

Reputation:

Try this:

Template.body.onCreated(function() {
  const self = this;
  self.autorun(() => {
    self.subscribe('features');
  });
});

Also, see https://guide.meteor.com/data-loading.html#organizing-subscriptions.

Upvotes: 1

Related Questions