Search code examples
node.jshandlebars.jsexpress-handlebarsnested-object

Handlebars - Nest objects in #each


I use express-handlebars with Node JS and I am trying to display informations from the array games on my HTML page using #each. But handlebars won't display the values inside my object. Even if it is not a nested object.

But if I only write {{this}}, it displays all the object like if it was a string. And if I do {{this.time}}, nothing is displayed.

I'm using Node JS v14.18.1, express v4.17.2 and express-handlebars v6.0.2.

Thank you in advance for your help !

    getHomePage: async (req, res) => {
        try {
            const games = await gameModel.find().sort({time: -1}).limit(3).populate('user');
            res.render('home', {title: 'Hello world', games});
        } catch (error) {
            console.error(error);
            res.status(500).json({error});
        }
    }
        <table>
            <thead>
                <th>Position</th>
                <th>Score</th>
                <th>Nom</th>
            </thead>
            <tbody>
                {{#each games}}

                    <tr>
                        <td>#{{@index}}</td>
                        <td>{{this}}</td>
                        <td>{{this.time}}</td>
                    </tr>

                {{/each}}
            </tbody>
        </table>

Solution

  • I thought the problem came from Handlebars or NodeJS. But it came from my MongoDB request.

    I resolved it by adding .lean() at the end of my Mongo request. By default, Mongo returns a document, not a javascript object. So we have to "convert" it to a javascript to allow handlebars to display it:

    gameModel.find().sort({time: -1}).limit(3).populate('user').lean()