dburles:collection-helpers

v2.0.0Published 2 weeks ago

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.

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

This will then allow you to do:

1const book = await Books.findOneAsync();
2const author = await book.authorAsync();
3author.firstName; // Charles
4author.fullName(); // Charles Darwin

and:

1const author = await Authors.findOneAsync();
2await author.books().fetchAsync();

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.

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

Testing

meteor test-packages ./

License

MIT