集合间的关联

As we discussed earlier, it's very common in Meteor applications to have associations between documents in different collections. Consequently, it's also very common to need to write queries fetching related documents once you have a document you are interested in (for instance all the todos that are in a single list).

To make this easier, we can attach functions to the prototype of the documents that belong to a given collection, to give us "methods" on the documents (in the object oriented sense). We can then use these methods to create new queries to find related documents.

集合帮助器Collection helpers

We can use the dburles:collection-helpers package to easily attach such methods (or "helpers") to documents. For instance:

Lists.helpers({
  // A list is considered to be private if it has a userId set
  isPrivate() {
    return !!this.userId;
  }
});

Once we've attached this helper to the Lists collection, every time we fetch a list from the database (on the client or server), it will have a .isPrivate() function available:

const list = Lists.findOne();
if (list.isPrivate()) {
  console.log('The first list is private!');
}

Association helpers

Now we can attach helpers to documents, it's simple to define a helper that fetches related documents

Lists.helpers({
  todos() {
    return Todos.find({listId: this._id}, {sort: {createdAt: -1}});
  }
});

Now we can easily find all the todos for a list:

const list = Lists.findOne();
console.log(`The first list has ${list.todos().count()} todos`);
``````

results matching ""

    No results matching ""