I'm currently in the process of setting up a blog and I want to create a page that displays the titles of all the articles I've written. For example:
List of Articles:
* Title: Article 1
* Title: Article 2
* Title: Article 3
Below is my Schema definition:
const ArticleSchema = new Schema({
title: { type: String, required: true },
author: { type: String, required: true },
content: { type: String, required: true },
});
Here's the function that sorts and presents each article on the ejs page.
exports.article_list = function (req, res, next) {
Article.find({}, "title author")
.sort({ title: 1 })
.populate("author")
.exec(function (err, list_articles) {
if (err) {
return next(err);
}
//Successfully executed, now rendering
res.render("article_list", {
title: "Article List",
article_list: list_articles,
});
});
};
And this is how I have coded it on my ejs page.
<ul>
<% article_list.forEach(function() { %>
<li>Title:<%= article_list.title %></li>
<% }); %>
</ul>
The code appears to be functioning properly as I have three test articles stored in my MongoDB database and three list items
are appearing on the page, however they are blank indicating that they may be displaying as undefined for some reason. Initially when I had
<%= article_list %>
on my ejs page, it displayed each object with the correct values but in JSON format.
{ _id: new ObjectId("641bf67f339b048733c05d2d"), title: 'First article', author: 'test' },
{ _id: new ObjectId("641d311570a689a1bf2a4c5d"), title: 'Second article', author: 'test' },
{ _id: new ObjectId("643252040d73d534661040b5"), title: 'Third article', author: 'test' }
I'm facing difficulty in getting it to display as desired which would just show the title of each article. Seeking guidance on this matter.