Alexander Mills
Alexander Mills

Reputation: 100426

Global variable in Meteor

I am trying to determine why my global variable isn't available in my browser console. Here is my top-level meteor javascript file contents:

     if (Meteor.isServer) {
        Meteor.startup(function () {

         Posts = new Mongo.Collection("posts");
         Carbrands = new Meteor.Collection("carbrands");
         Comments = new Mongo.Collection("comments");

         Posts.insert({post1:'post'});
         Carbrands.insert({post1:'post'});
         Comments.insert({post1:'post'});
      });
     }

(I can confirm that Posts, Carbrands, Comments are defined), but in the broswer, I get this (Posts is undefined):

enter image description here however, when I add this line of code at the top:

Posts = null;

     if (Meteor.isServer) {
         Meteor.startup(function () {

      Posts = new Mongo.Collection("posts");
      Carbrands = new Meteor.Collection("carbrands");
      Comments = new Mongo.Collection("comments");

      Posts.insert({post1:'post'});
      Carbrands.insert({post1:'post'});
      Comments.insert({post1:'post'});
      });
     }

I get the following console output (Posts is null):

enter image description here

what gives?

Upvotes: 0

Views: 2426

Answers (2)

Ethaan
Ethaan

Reputation: 11376

Try declaring Collections inside the /lib folder

So they will be available both client/server

Like Meteor docs says /lib folder its a good place to declare collections

lib/ # common code like collections and utilities

Upvotes: 3

David Weldon
David Weldon

Reputation: 64342

The code inside of the Meteor.isServer is only running on the server (not on the client). You need to define you collections outside of that check so they will be exposed to both.

Posts = new Mongo.Collection("posts");

if (Meteor.isServer) {
  // do server things. Posts will be defined here.
}

if (Meteor.isClient) {
  // do client things. Posts will be defined here.
}

As you codebase expands beyond a single file, you'll end up dividing it into directories like this. In which case, your collection defintion will end up somewhere like lib/collections/posts.js, and will automatically be exposed to both the server and the client.

Upvotes: 3

Related Questions