NlHell
NlHell

Reputation: 33

How to do foreach in Meteor with Mongo?

Have collection

 Peoples = new Mongo.Collection('peoples');

    Peoples.insert({
        name: ["Mark", "John", "Kate"]
    });

I want to show all names in name

<template name="pTable">
  <tr class="trJob">
    <td>
      {{#each names}}
          {{> peopleName}}
      {{/each}}
    </td>
  </tr>
</template>

<template name="peopleName">
    <div>{{name}}</div>
</template>

What in my Temlate helpers

Template.pTable.helpers({
  names: function(){
    return Posts.tags;
  }
});

Template.peopleName.helpers({
  name: function(){
    return Posts.tags.find();
  }
});

I know that i have sh*** code in my Template helpers, any idea how to make it good ?

It must look like (in DOM)

<td>
  <div>Mark</div>
  <div>John</div>
  <div>Kate</div>
</td>

Upvotes: 1

Views: 144

Answers (2)

Billybobbonnet
Billybobbonnet

Reputation: 3226

Since you have different names for your collection, I will stick with the first one Peoples

Here is how I would proceed with your helpers:

Template.pTable.helpers({
  names: function(){
    return People.find({_id:yourId},{fields:{name:1}}).fetch();
  }
});

And your peopleName template would be like this:

<template name="peopleName">
    <div>{{this}}</div>
</template>

If you need to get all the names of all your documents, I need to nest your {{#each names}} into another {{#each doc}} where doc helper is like this (updated names as well) :

Template.pTable.helpers({
     doc: function(){
        return People.find().fetch();
      },
    names: function(){
            return People.find({_id:this.id},{fields:{name:1}}).fetch();
    });

Upvotes: 1

Zeev G
Zeev G

Reputation: 2221

simple array example

Template.home.helpers({
  names: function(){
    return [1,2,3];
  }
});

<template name="home">
      {{#each names}}
        {{this}}
      {{/each}}
</template>

will print:

1 2 3

each item becomes "this" inside the each loop. if you call another template within the loop, then its "this" will be populated by the item

Upvotes: 1

Related Questions