Search code examples
mongodbmeteorcollectionscoffeescriptreferenceerror

Meteor Collection exists in Mongo but returns ReferenceError in browser console


I'm setting up a new Meteor project and am having trouble working with collections on the client side. Right now what I'm building is an administrative page where a user can maintain a list of schools.

Running meteor mongo and db.schools.find() in Terminal returns a BSON object just as I would expect, however when I enter "Schools" in the Chrome console it returns Uncaught ReferenceError: Schools is not defined which is a bummer.

My project architecture (simplified to the bits that reference the School collection) is as follows:

client/
  layouts/
    admin/
      schools.coffee
      schools.jade
  lib/
    subscriptions.coffee
lib/
  collections.coffee
server/
  lib/
    publications.coffee

The contents of each of these files (in the desirable load order) is:

1) lib/collections.coffee

 1| Schools = new Mongo.Collection('schools')

2) server/lib/publications.coffee

 1| Meteor.publish('schools'), ->
 2|   Schools.find()

3) client/lib/subscriptions.coffee

 1| Meteor.subscribe('schools')

4) client/layouts/admin/schools.coffee

76| Template.admin_schools.helpers
77|   schools: ->
78|     Schools.find()
79|   numSchools: ->
80|     Schools.find().count()
81|   hasSchools: ->
82|     Schools.find().count() > 0

5) client/layouts/admin/schools.jade

 4| h2.admin__header Schools
 5|   span.admin__record-count {{numSchools}} entries
...
22| table.admin__list
23|   if hasSchools
24|     each schools
25|       tr.admin__list-item
26|         td #{name}

I also have a form for new collection entries which calls Schools.insert, but the error there is the same.

When the page loads, I get the following error (likely because it is called first):

debug.js:41 Exception in template helper: ReferenceError: Schools is not defined
at Object.Template.admin_schools.helpers.numSchools

Those two errors, combined with the fact that I know there exists an entry in the collection, leads me to believe that the issue lies with the client side's awareness of the existence of the collection.

This discrepancy might possibly be due to load order (I am pretty sure I accounted for that by putting the important files in lib/ directories, though I would love a second opinion), or maybe due to a spelling/syntax mistake (though the absence of compile errors is puzzling). Maybe something completely different!

Thank you very much for your time and assistance, they are much appreciated.


Solution

  • Turns out that because this is CoffeeScript, placing an @ before Schools = new Mongo.Collection('schools') in lib/collections.coffee makes Schools a global variable, thereby solving the problem! Pretty simple fix in the end :)

    Special thanks to Kishor for helping troubleshoot.