Question about file structure -- Mongo.Collection();

I just got done doing the simple-todo tutorial and I am now moving the files into their own folders/files based on http://docs.meteor.com/#/full/structuringyourapp everything is easy to follow except one and that is where do you usually place Tasks = new Mongo.Collection('tasks');?

In my projects collections usually end up in ā€œlibā€ folder, or mby in ā€œbothā€ now when there is some stuff to put there for SSR.

1 Like

All JavaScript files outside special directories are loaded on both the client and the server. Thatā€™s the place for model definitions and other functions. Meteor provides the variables Meteor.isClient and Meteor.isServer so that your code can alter its behavior depending on whether itā€™s running on the client or the server.
- ( Meteor API Documentation )

This means you can place these where you want them, unrestricted by Meteor. As @shock mentioned, you can use the foldernames lib, both or your-custom-folder, if you want the collection to be accessible from the client (minimongo) and the server (mongodb).

1 Like

To add to the existing answers, I place them under a globally defined var to reduce polluting my global namespace.

## _.js // for file load order
db = {};

## tasks.js
db.Tasks = new Mongo.Collection('tasks');
db.Tasks.attachSchema(...); // attach schema
db.Tasks.helpers({ ... }) // attach collection helpers
db.Tasks.before.insert(function () {...}) // attach collection hooks

I put the schema, helpers and hooks all in the same file to keep all collection related logic together each collection.

2 Likes

Interesting suggestions. Thanks guys. Iā€™m following method 1 for organizing y project. Where do you guys usually dump your routes?

My structure looks like thisā€¦

home/
home/lib
home/methods
home/client
home/client/events
home/client/helpers
home/server
home/routes
home/home.html

Not sure if this is the standard way or not.

I only speak for myself, but since I started moving all collection logic into one file, I started doing the same for route/template/helper/events logic too so now my ā€˜pageā€™ file looks like this:

## taskList.js
Router.route('taskList', ...)

//if you use autoforms
AutoForm.hooks({...})

// template logic
Template.taskList.onCreated({...})

Template.taskList.helper({...})

Template.taskList.events({...})

I used to have a separate file just for routes, one for hooks but that meant i was jumping all over the place for template logic. Now I just have my jade template, my template logic and my collection/schema open.

This will help if you ever want to modularize into packages in the distant distant futureā€¦ :slight_smile: but letā€™s not create more problems just now

1 Like

Not sure if this is the standard way or not.

In Meteor, there is no standard. However, where you place files and how you name them, can affect the load order. I know, it feels weird at firstā€¦

1 Like