Abe Miessler
Abe Miessler

Reputation: 85096

Collection empty when accessed from rendered event?

I have a collection that I am subscribing to, but when I attempt to access it from my onRendered event it always returns as an empty array. Below is the method I am using:

FlightCounts = new Mongo.Collection("flightCounts");

if (Meteor.isClient) {
  Meteor.subscribe('flightCounts');
  Template.hello.rendered = function(){
    var counts = FlightCounts.find().fetch()
    console.log(counts)
  }

}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
    Meteor.publish('flightCounts', function(){
      return flightCounts.find();
    })
  });
}

Can anyone see why my collection would always be empty here? Any suggestions on how to get it populated?

Upvotes: 1

Views: 108

Answers (3)

Jeremy S.
Jeremy S.

Reputation: 4649

The underlying issue is that the publish function should reference Meteor's Mongo.Collection name, FlightCounts, and not the raw db.collection name flightCounts:

Meteor.publish('flightCounts', function(){
  return FlightCounts.find();
});

I also agree with the prior answer that your template should check to ensure the subscription is ready before logging the data, otherwise it may not have arrived yet:

Template.hello.onRendered(function(){
  this.autorun(() => {
    let ready = Template.instance().subscriptionsReady();
    if (!ready){ return; }
    let counts = FlightCounts.find().fetch();
    console.log(counts);
  });
});

(Note that the newer syntax for Template.name.rendered is Template.name.onRendered().)

Upvotes: 2

Thai Tran
Thai Tran

Reputation: 9935

Alternatively, you can use subscriptions of FlowRouter or waitOn of IronRouter to put the subscribe there

Update Surprisingly, IronRouter now has the subscriptions option as well

Upvotes: 1

Kishor
Kishor

Reputation: 2677

if (Meteor.isClient) {
    Meteor.subscribe('flightCounts');
    Template.hello.rendered = function() {
        var template = this;
        template.autorun(function () {
             var counts = FlightCounts.find().fetch()
             console.log(counts)
        });
    }
 }

Your collection is not populated because, it is still getting data from server. So you should wrap your code inside an autorun, so that it will re-run whenever data is updated.

P.S: I am on mobile, so formatting may not be proper. Sorry about it.

Upvotes: 2

Related Questions