Warning: this post is old and might not reflect the current state of the art

An application typically needs to display data of some sort.

Be it messages, comments, posts, books, addresses, pictures.. everything is a collection of something.

Meteor being deeply integrated with MongoDB takes the Mongo databae collection concept and takes it to the application level.

In both the client and server contexts, you’ll typically interact with data by interacting with data collections.

How does it work?

Create your first collection

Messages = new Mongo.Collection('messages');

This defines a global variable messages, which will be visible across the entire App on client and server.

P.s. On some old tutorials (pre 0.9.1) you’ll see new Meteor.Collection(..). This is a deprecated syntax but it will still work for now.

This code needs to run on both the client and the server, so you’ll put it for example under collections/messages.js.

While the code running in the two environments is the same, what it does is different:

  • on the server it creates a Mongo collection if it’s not already existing, and then it will load the cursor in the Messages variable
  • on the client it will instantiate a Minimongo local collection. The app once instantiated will link that to the server-side collection, and will automatically keep them in sync.


Adding items to a collection

You’ll be able to insert items into a collection using the .insert() method on the collection cursor:

Messages.insert({message: "Hi"});

Showing the collection in the template

In a template you can use the {{#each}} Spacebars helper to navigate the collection and print all values stored in it:

<template name="messages">
  {{#each messages}}
    {{message}}
  {{/each}}
</template>

Want to hire me?

I'm currently considering remote job/contract opportunities as a Frontend Developer.

Read more about me and if you're interested, get in touch.