Sandro Palmieri
Sandro Palmieri

Reputation: 1203

Accessing Object in an array with Blaze using Spacebars in a Meteor application

I am trying to iterate in my template a list of objects included in an array field of a Mongo DB document using the Meteor platform.

So for example I create a MongoDB Posts collection of documents with the following JSON structure:

 _id: "xyxyxyxy",
 title: "my first post",
 description: "a very intresting post",
 comments:[
           {comment:"a very cool post"},{createdBy: Meteor.userId()},
           {comment:"I don't like this post"},{createdBy: Meteor.userId()}
          ]

Every logged-in user can add a comment that will be listed under the title and the description of a single post detail view.

So I set my template helper in my js file and added {{#each}} spacebars helper in my HTML file.

When I try to iterate the post document I get the title, the description but cannot get the values of my nested objects (comments). Instead, I get the following expression: "Object object".

How can I access those values so that I can show the comments related to the post and the user who added the comment? Thanks

Please note: I am not using aldeed simple-schema and not using pub/sub pattern. As of now I am intrested in understanding the templating part of the framework.

Upvotes: 0

Views: 559

Answers (3)

dtm7
dtm7

Reputation: 361

similar case using meteor-blaze where I have users database with structure like below:

"_id": "abcdefojsdoijfodsjoijfe",
"username": "testuser",
"emails" : [ 
           { "address": "[email protected]",
             "verified": "false"} 
]

The nested each solution like provided by Philip Pryde above will work perfectly as the calling for database such as emails.address won't work.

So if I want to display username and email address, need to do like below

{{#each usernames}}
<p>your username: {{username}}</p>
{{#each emails}}
<p>your email: {{address}}</p>
{{/each}}
{{/each}}

Upvotes: 0

Philip Pryde
Philip Pryde

Reputation: 940

You will need to have two {{#each}}, one to iterate over the Posts and then one inside that to iterate over comments because they are in an array structure, using the below you shouldn't need to change or define any new template helpers:

{{#each posts}}
  {{title}}
  {{description}}
  {{#each comments}}
    {{createdBy}}
    {{comment}}
  {{/each}}
{{/each}}

Upvotes: 1

Julien Leray
Julien Leray

Reputation: 1687

That's normal, I don't know why you've wrapped your inner object comment into array, you should have this structure:

_id: "xyxyxyxy",
 title: "my first post",
 description: "a very intresting post",
 comments:[
           {comment:"a very cool post",createdBy: Meteor.userId()},
           {comment:"I don't like this post",createdBy: Meteor.userId()}
 ]

Upvotes: 0

Related Questions