dburles:collection-helpers

v1.0.2Published 9 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

Meteor Collection Helpers

Collection helpers automatically sets up a transformation on your collections using Meteor's Mongo.Collection transform option, allowing for simple models, with an interface similar to template helpers.

Installation

$ meteor add dburles:collection-helpers

Usage

It's recommended to set up helpers to run on both server and client. This way your helpers can be accessed both server side and client side.

Some simple helpers:

1Books = new Mongo.Collection('books');
2Authors = new Mongo.Collection('authors');
3
4Books.helpers({
5  author: function() {
6    return Authors.findOne(this.authorId);
7  }
8});
9
10Authors.helpers({
11  fullName: function() {
12    return this.firstName + ' ' + this.lastName;
13  },
14  books: function() {
15    return Books.find({ authorId: this._id });
16  }
17});

Example use within a template

Our relationships are resolved by the collection helper, avoiding unnecessary template helpers. So we can simply write:

1Template.books.helpers({
2  books: function() {
3    return Books.find();
4  }
5});

...with the corresponding template:

1<template name="books">
2  <ul>
3  {{#each books}}
4    <li>{{name}} by {{author.fullName}}</li>
5  {{/each}}
6  </ul>
7</template>

Use outside of templates

You can of course access helpers outside of your templates:

1Books.findOne().author().firstName; // Charles
2Books.findOne().author().fullName(); // Charles Darwin

Meteor.users

You can also apply helpers to the Meteor.users collection

1Meteor.users.helpers({
2  // ...
3});

Applying the transformation function

Sometimes it may be useful to apply the transformation directly to an object.

1var doc = {
2  firstName: 'Charles',
3  lastName: 'Darwin'
4};
5
6transformedDoc = Authors._transform(doc);
7
8transformedDoc.fullName(); // Charles Darwin

License

MIT