Search code examples
meteorspacebarsmeteor-helper

How Do I Join Data From Two Collections Using Spacebars?


I have a template (tmpl1) which refers to a collection projectdetails, in the following code I can successfully show {{detailname}} what is based on the collectiondata projectdetails.detailname But now I need to show also the Projectname which is in projects.name I do have the project._id saved in projectdetails.projectId How can I now define a handelbar like {{projectName}} to display the project name. I have tried to define this in projectdetails.js as helper but I was not successful. Can someone please add a code sniplet which explains how to define the handelbar and how to retrieve the data?

<template name="tmpl1">
<div id="example" class="panel">
    <ol class="breadcrumb">
        <li><a href="/"><i class="fa fa-home"></i> Start</a></li>
        <li><a href="/dashboard"><i class="fa fa-cubes"></i> Projekte</a></li>
        <li><a href="{{pathFor 'details'}}"><i class="fa fa-cogs"></i> Details</a></li>
        <li class="active">{{detailname}} {{projectName}}</li>
    </ol>
</div>


Solution

  • You can just add a helper for projectName which joins the two collections.

    The context of your template appears to be a "project detail" document, so inside of the projectName helper, this.projectId should be the id of the project document. Assuming the collection is called Projects and each project has a name field, the code should look something like this:

    Template.tmpl1.helpers({
      projectName: function() {
        var project = Projects.findOne(this.projectId);
        return project && project.name;
      }
    });