I am a newbie NodeJS developer and I am trying to fetch data from MongoDB and render it to another .ejs file to display it. But error showing that data is not defined in the line <% data.forEach(post => { %>
main.js:
const express = require('express');
const router = express.Router();
const Post = require('../models/posts');
router.get('', async (req, res) => {
const locals = {
title: 'Blog Post',
description: "A blog website created using Node.js, Express, and MongoDB."
}
try {
const data = await Post.find();
res.render('index', { locals, data });
}
catch(err) {
console.error(err);
res.status(500).send("Server Error");
}
});
module.exports = router;
index.ejs:
<ul class="article-ul">
<% data.forEach(post => { %>
<li>
<a href="">
<span><%= post.title %> </span>
<span class="article-list__date"> <%= post.createdAt %> </span>
</a>
</li>
<% }) %>
</ul>
I am trying to send data from main.js to index.ejs file but could not succeed.
New contributor
Abir Rahman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2