Making sure a collection exists

As an example, I have a shared directory called /collections that contains a file named client_collections.js, which looks like this:

client_collections = new Mongo.Collections('client_collections');

On the client, in an event, I attempt to use client_collections, but I get an exception when trying to do so.

What’s the best way to make sure a collection exists?

I think I’ve seen something like a check on Meteor.startup, but can’t find an example – besides, even if this is one way to make sure a collection exists, is this the right way?

1 Like

the directory /collections might get parsed after your client code, thus the client_collection might not be defined by the time you are trying to access it. The lib directory is the one that gets parsed before all others, maybe that is where you should put your client_collections.js file.

Look at the docs about structuring your app and special directories

Thanks. I don’t see the lib directory mentioned in the docs link you posted.

Also, is collectionname = new Mongo.Collections… In the lib directory enough to ensure the collection exists or is additional code required?

Example File Structure

The file structure of your Meteor app is very flexible. Here is an example layout that takes advantage of some of the special folders mentioned above.

lib/                      # common code like collections and utilities
lib/methods.js            # Meteor.methods definitions
lib/constants.js          # constants used in the rest of the code

client/compatibility      # legacy libraries that expect to be global
client/lib/               # code for the client to be loaded first
client/lib/helpers.js     # useful helpers for your client code
client/body.html          # content that goes in the  of your HTML
client/head.html          # content for  of your HTML:  tags, etc
client/style.css          # some CSS code
client/.html     # HTML templates related to a certain feature
client/.js       # JavaScript code related to a certain feature

server/lib/permissions.js # sensitive permissions code used by your server
server/publications.js    # Meteor.publish definitions

public/favicon.ico        # app icon

settings.json             # configuration data to be passed to meteor --settings
mobile-config.js          # define icons and metadata for Android/iOS

Defining the collection on client and server is enough.

I have the collection defined in a /collection directory, which is shared between the client and server – I thought this was enough. But it seems not to be. Your first suggestion was to place it in the declaration in the lib directory, right? I’ll give that a try.

should be

Mongo.Collection

Oh, I’ll have to go back and see if that’s a cut and paste from the code or if I wrote that out by hand wrong

Thanks for that catch.

That was just a typo — my code is correct.