Meteor - Using collection on client startup

Tags: meteor
By : pomber
Source: Stackoverflow.com
Question!

Why this code shows "0"? Shouldn't it return "1"?

Messages = new Meteor.Collection("messages");

if (Meteor.is_client) {
    Meteor.startup(function () {    
        alert(Messages.find().count());
    });
}

if (Meteor.is_server) {
    Meteor.startup(function () {
        Messages.insert({text: "server says hello"});
    });
}

If I do the "Messages.find().count()" later, it returns 1.

By : pomber


Answers

Just to follow up with a code example of how to know when a collection is ready to use on the client.

As @debergalis described, you should use the Meteor.subscribe approach - it accepts a couple of callbacks, notably onReady

For example:

if(Meteor.isClient){

    Meteor.subscribe("myCollection", {

        onReady: function(){

            // do stuff with my collection

        }

    });

}
By : danwild


This video can help you solving your question :)
By: admin