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
        });
});
Antonio
  • 112
  • 1
  • 8

3 Answers3

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 });
Andy
  • 81
  • 5
  • here is the code you asked for: `Idea.find({}) .sort({ date: 'desc' }) .then(ideas => { res.render('ideas/index', { ideas: ideas }); });` – Antonio Jan 20 '20 at 14:09
  • 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. – Andy Jan 20 '20 at 16:22
0

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

Antonio
  • 112
  • 1
  • 8
0

The code provided can solve

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