Search code examples
arraysnode.jsexpresshandlebars.jsexpress-handlebars

Can't show array on index using handlebars on a NodeJs+Express server


I've a problem using handlebars that I'm not able to solve, today it's the second day trying to solve it but I'm really stuck.

I'm trying to use handlebars for the first time because I wanted to make the web page I'm working on a bit more dynamic.

On my server I got a mongoDB, there is this search button where the user inputs whatever they want and they have to get user info from any user that match.

The response of that query comes like this:

_id: 5e2201a99162aa0344ed4261,
userName: 'Example',
email: '[email protected]',
age: '23'

What I'm trying to do is get that data and show it on a div on users dom but for some reason I'm not being able to do it.

On my index.js file on the node server I got this function:

const printSearch = user => {
  console.log(user);
  res.render("main", {
    layout: "index",
    users: user
  });
};

This function is a callback function of the one that do the query and I know that on this function, user has the result of that query inside because of the console.log(user);.

Then on main.hbs I have the following code:

<div id="result">
  {{#if users}}
    {{#each users}}
      <p>{{users.userName}}</p>
      <p>{{users.email}}</p>
      <p>{{users.age}}</p>
    {{/each}}
  {{/if}}
</div>

But for some reason that doesn't work, as I said before, this is my first time using handlebars so I imagine that there is something I'm missing but I'm not being able to figure it out.

It would be really helpful a bit of help in here, I'll be really glad.

Thanks in advance everyone!


Solution

  • To access the current iteration value, don't use {{users.<property>}}, just: {{property}}. If users is an array do:

    {{#each users}}
          <p>{{userName}}</p>
          <p>{{email}}</p>
          <p>{{age}}</p>
    {{/each}}
    

    Otherwise if users is a single object you can drop {{#each}}

    <p>{{users.userName}}</p>
    <p>{{users.email}}</p>
    <p>{{users.age}}</p>