流星中的全局变量

时间:2015-02-04 00:58:24

标签: javascript node.js meteor

我正在尝试确定为什么我的全局变量在我的浏览器控制台中不可用。这是我的顶级流星javascript文件内容:

     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'});
      });
     }

(我可以确认帖子,Carbrands,评论已定义),但在broswer中,我得到了这个(帖子未定义):

enter image description here 但是,当我在顶部添加这行代码时:

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'});
      });
     }

我得到以下控制台输出(帖子为空):

enter image description here

是什么给了什么?

2 个答案:

答案 0 :(得分:3)

Meteor.isServer内的代码仅在服务器上运行(不在客户端上)。您需要在该检查之外定义集合,以便将它们暴露给两者。

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.
}

当您的代码库扩展到单个文件之外时,您最终会将其划分为this之类的目录。在这种情况下,您的收藏定义将在lib/collections/posts.js之类的某个位置结束,并将自动向服务器和客户端公开。

答案 1 :(得分:2)

尝试在/lib文件夹

中声明收藏集

因此,client/server

可以使用它们

Meteor docs说明/lib文件夹一样,它是宣传馆藏的好地方

  

lib /#常用代码,如集合和实用程序