dburles:collection-helpers

v1.1.0Published 8 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 that's similar to template helpers.

Installation

$ meteor add dburles:collection-helpers

Usage

Write your helpers somewhere seen by both client and server.

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

This will then allow you to do:

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

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

1Template.books.helpers({
2  books() {
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>

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
6var transformedDoc = Authors._transform(doc);
7
8transformedDoc.fullName(); // Charles Darwin

License

MIT