在Meteor.startup之前未加载的独立文件中声明的集合在Meteor应用程序中运行服务器端

我刚开始在Mac上使用Meteor。 我做了一个简单的应用程序,在服务器目录中有两个.coffee文件:bootstrap.coffee和publish.coffee。

bootstrap.coffee的内容如下所示:

Meteor.startup -> if RaceDays.find().count() is 0 

等等。

publish.coffee的内容是:

 RaceDays = new Meteor.Collection("racedays") Meteor.publish "racedays", -> RaceDays.find() 

问题是当我用meteor命令运行应用程序时出现以下错误:

 20130917-15:42:00.967(1)? (STDERR /Users/gnidde/Projects/test/.meteor/local/build/programs/server/boot.js:184 W20130917-15:42:00.970(1)? (STDERR) }).run(); W20130917-15:42:00.971(1)? (STDERR) ^ W20130917-15:42:00.979(1)? (STDERR) ReferenceError: RaceDays is not defined W20130917-15:42:00.980(1)? (STDERR) at server/q.coffee:3:5 W20130917-15:42:00.981(1)? (STDERR) at mains (/Users/gnidde/Projects/test/.meteor/local/build/programs/server/boot.js:157:61) W20130917-15:42:00.981(1)? (STDERR) at Array.forEach (native) W20130917-15:42:00.982(1)? (STDERR) at Function._.each._.forEach (/Users/gnidde/.meteor/tools/3cba50c44a/lib/node_modules/underscore/underscore.js:79:11) W20130917-15:42:00.984(1)? (STDERR) at /Users/gnidde/Projects/test/.meteor/local/build/programs/server/boot.js:157:5 

看起来,Meteor.startup是在publish.coffee文件被加载之前运行的,但是如果我正确地理解了文档,情况就不应该如此。 我也试图改变它使用.js文件,而不是没有区别。

如果我删除了publish.coffee文件,并将代码放在bootstrap.coffee文件的顶部,它就起作用了。

什么可能是错的?

您需要使用@将coffeescriptvariables声明为全局variables:

 @RaceDays = new Meteor.Collection("racedays"); 

这是由于Meteorvariablesshadowing如何与coffeescript自动variables声明相关。

在Meteor的简单Javascript中,用var声明的variables绑定到它们声明的文件:

 var LocalRaceDays = ...; // this is visible only in the file it's defined RaceDays = ...; // this is visible everywhere 

显然,所有的集合都应该以第二种方式来定义。

但是,默认情况下,coffeescript会自动执行“智能”variables声明 – 基本上通过将var variableName放置在JavaScript中variables可见的第一位。 在你的情况下,这会导致RaceDays由js中的var声明,因此它们的作用域是文件。

使用@ char通过将variables绑定到this globalwindow对象来取代这个默认行为。