Reputation: 2049
Doing some experimenting to get a grasp of the basics on my road to learning how to code. Been messing around with one aspect all day but can't figure it out. I'm sure it must be something simple and would appreciate any help!
So I've created a Mongo collection:
Posts = new Mongo.Collection('posts');
I then added 3 documents into the collection, with 2 fields each (name and quantity). Now, when in the Google Chrome console I run:
Posts.find().count();
//returns '3' as expected
However, when instead I run the following code from the server (is it called the server if it is the client side code?):
if (Meteor.isClient) {
var c = Posts.find().count();
console.log("The database documents count is " + c);
}
Then it comes up on Chrome console as:
The database documents count is 0
What gives? What's going on here?
Thanks in advance!!
Upvotes: 1
Views: 76
Reputation: 8163
How it works: when you open a page, the client has no data at all. After your JS is loaded, publish functions begin to work and after some time, when publishing is over, you have data on the client.
So at the moment when browser runs:
if (Meteor.isClient) {
console.log(Posts.find().count());
}
You have no data on the client, that's why you see 0
in the console.
But then you open console manually and write Posts.find().count()
. It took some time for you to open the console, to write Posts.find().count()
and this time was enough for publish functions to send all data to the client, so now you have data on the client and you will see 3
in the console.
You can try this experiment:
if (Meteor.isClient) {
setTimeout(function() {
console.log(Posts.find().count());
}, 2000);
}
It will log posts count not immediately, but with 2 seconds delay, this should be enough for publishing to be over and you will see 3
in the console. You can change timeout delay and find out how much does it take for the server to send posts data to the client.
Upvotes: 1