Handlebars rendering empty elements when data is passed to partial

Viewed 150

I have been stuck on this issue for a while and don't know what to do anymore. I have data stored in mongoDB and all I am trying to do is render out the data into a partial I have created. I deleted everything in the partial and still get this issue, so I think it's somewhere in retrieving the data and looping over it

Problem 1: When I render the content, it will render, but I will also have 5-6 empty elements, whether it's a p tag, h1, img etc.

Problem 2: When I add a class to an img tag, it is being applied as the src for the empty tags app js:


const bodyParser = require('body-parser')
const { Console } = require('console')
require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const app = express()
const exphbs = require('express-handlebars')
const path = require('path')
const indxRoutes = require('./routes/index')

//Templataing engine
app.engine('handlebars', exphbs({defaultLayout: 'layout'}))
app.set('view engine', 'handlebars');
app.use(express.static(path.join(__dirname, '/public')));

app.use(indxRoutes)

mongoose.connect(process.env.DB_CONNECTION, () => {
    console.log('database connected')
})





app.listen(3000)

my route:

var express = require('express')
var router = express.Router()
var Product = require('../models/product')

router.get('/', (req, res) => {
    Product.find((err, docs) => {
        console.log(docs)
        if(err){
            res.send('error')
        }
        res.render('index', { products: docs})
    })
})

module.exports = router;

my now deleted partial:


{{# each products}}
    {{# each .}}
 
        {{this.title}}
        {{this.description}}
        {{this.price}}
        
        <img src={{this.imagePath}} class="card-img">
      

    {{/each}}
    
{{/each}}

The problem is, this works, but I'm also getting 5-6 empty img tags that looks like this

<img src="class="card-img"">

and I'll get 5-6 empty tags if I create another element like p, h1 etc

I really hope this makes sense. Thanks for any and all help.

1 Answers

So I figured it out. Basically, I was sending the data that was received from mongo db to the template but instead I did this:

router.get('/', (req, res) => {
    Product.find((err, docs) => {
        let newDocs = JSON.stringify(docs)
        console.log(newDocs)
        let newDocss = JSON.parse(newDocs)
        console.log(newDocss)
        res.render('index', { products: newDocss})
    })
})

I console logged every step. Essentially just strinigfy and parse and it worked. I wish I could give a more detailed answer but I'm still learning.

My guess is mongoDB stores data in BSON. By using stringify, it gets converted to JSON, then parsing the JSON data, we can get back an array we can work with.

Can anyone confirm if this is correct thinking?

Related