Skip to content Skip to sidebar Skip to footer

Returning Subdocument Array Through Meteor / Mongo

I'm having a little trouble returning and displaying tags that I'm adding to a subdocument. I have no problem adding tags, but want to put a label on the item for each tag. I simpl

Solution 1:

Your only problem is trying to iterate a cursor and a sub array within the same each block. If you separate your items template and an individual item template, you'll end up with your desired result.

For the sake of simplification, I altered your code to look like this:

This is your main body:

<body>
    {{> items}}
</body><templatename="items">
  {{#each items}}
    {{> item}}
  {{/each}}
</template><templatename="item"><h2>{{itemText}} tags are:</h2><ul>
  {{#each itemTags}}
    <li>{{this}}</li>
  {{/each}}
  </ul></template>

And this is your helper:

Template.items.helpers({
  items: function() {
    return Items.find();
  }
})

Assuming an item document looks like:

{ 
  itemText: String,
  itemTags: Array
}

I've created an app on Meteorpad for you to play with:

http://meteorpad.com/pad/BmRQ5fkwWEMBKszJW/SO-27951102

you can further alter the code there and see the changes in realtime. It is basically jsfiddle for meteor.

Edit: inspired by @chip-castle's comment, you can in fact use a single template with nested each blocks:

<template name="items">
  {{#each items}}
    <h2>{{itemText}} tags are:</h2>
    <ul>
    {{#each itemTags}}
      <li>{{this}}</li>
    {{/each}}
    </ul>
  {{/each}}
</template>

But using separate templates is more flexible in both design and handling events where necessary.

Solution 2:

Do you have a publication and subscription setup?

server/publications.js

Items = newMongo.Collection("items");

Meteor.publish("items", function () {
  returnItems.find({});
});

client/subscriptions.js

Items = new Mongo.Collection("items");

Meteor.subscribe("items");

Post a Comment for "Returning Subdocument Array Through Meteor / Mongo"