0

Even after looking at how-to-iterate-over-array-of-objects-in-handlebars, I could not make it work. I am using mongoose model, and want to simply iterate over objects and display both title and details:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const IdeaSchema = new Schema({
title: {
    type: String,
    required: true
},
details: {
    type: String,
    required: true
},
date: {
    type: Date,
    default: Date.now
}
});

mongoose.model('ideas', IdeaSchema);

Here is my handlebars template:

{{#each ideas}}
        <div class="card card-body">
            <h4>{{title}}</h4>
            <p>{{details}}</p>      
        </div>
{{/each}}

It displays 2 empty divs with no content inside:

<div class="card card-body">
    <h4></h4>
    <p></p>      
</div>
<div class="card card-body">
    <h4></h4>
    <p></p>      
</div>

Here is the code that loads the collection

Idea.find({})
    .sort({ date: 'desc' })
    .then(ideas => {
        res.render('ideas/index', {
            ideas: ideas
        });
});

3 Answers 3

0

You didn't provide the code snippet where you are populating the variable ideas and setting up handlebars. Please provide that, or if you aren't doing so, start with this:

You need to assign and likely export (if used in a different module) the model Mongoose is compiling for you like:

export const IdeaModel = mongoose.model('ideas', IdeaSchema);

and then use that to populate the variable ideas like:

const ideas = IdeaModel.find({}); // fetch all ideas or add query criteria

Then pass ideas into the handlebars template function like:

const html = template({ ideas });
Sign up to request clarification or add additional context in comments.

2 Comments

here is the code you asked for: Idea.find({}) .sort({ date: 'desc' }) .then(ideas => { res.render('ideas/index', { ideas: ideas }); });
Check if the query is returning the data using console.log or a debugger. If it is, you'll need to consult the docs for whatever express middleware you're using and/or post the code that sets up the middleware.
0

I got fixing this issue by by installing a dev dependency for handlebars. See details on https://stackoverflow.com/a/59704492/3141885

Comments

0

The code provided can solve

dbName.find({}).lean().then((ideas) => {
 res.render('ideas/index', { ideas: ideas });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.