Checking for collection instance

I keep getting these strange errors in my Tracker.autorun’s.

Basically, the error is that my collection is not defined. I suspect this has to do with race condition where I’m trying to reference a collection name that has not be instantiated (yet).

To isolate the issue:

I have the following directory structure and code as an example:

root/client/trackers/

Tracker.autorun(function () {

var payment = Meteor.subscribe('some_published_document', Session.get('some_id'));

if (payment.ready()) {
  var collection_published = collection_name_of_published.findOne({userId: Session.get('some_id}); // <-- undefined: collection_name_of_published
  if (collection_published && collection_published.field) {
    // do stuff
  }
}
});

root/collections/

collection_name_of_published = new Mongo.Collection('collection_name_of_published');

So is this that because my collection is defined in a directory further up the directory structure in root/collection is getting instantiated AFTER the Tracker further down the directory structure in root/client/trackers? And because of even though the subscription is ready, on the client the collection name doesn’t exist yet?

Or could it be that in one case the Session.get(‘some_id’) is null, and the subscription is ready but returns nothing, so the collection is empty on the client? But in this case I don’t see how this will cause the collection_name_of_published to be undefined.

If I check for the collection instance like so:

Tracker.autorun(function () {

var payment = Meteor.subscribe('some_published_document', Session.get('some_id'));

if (payment.ready()) {
  if (collection_name_of_published) {
    var collection_published = collection_name_of_published.findOne({userId: Session.get('some_id}); // <-- undefined: collection_name_of_published
    if (collection_published && collection_published.field) {
      // do stuff
    }
  }
}
});

Then will the // do stuff ever run again after it checks the first time and the Session hasn’t changed?

Try putting your collections in a folder like (project root)/lib/collections. This has to do with the load order that meteor uses.

The JavaScript and CSS files in an application are loaded according to these rules:

  • Files in the lib directory at the root of your application are loaded first.

  • Files that match main.* are loaded after everything else.

  • Files in subdirectories are loaded before files in parent directories, so that files in the deepest subdirectory are loaded first (after lib), and files in the root directory are loaded last (other than main.*).

  • Within a directory, files are loaded in alphabetical order by filename.
    These rules stack, so that within lib, for example, files are still loaded in alphabetical order; and if there are multiple files named main.js, the ones in subdirectories are loaded earlier.

1 Like

This seemed to have remove the race condition, thanks!