EJS not displaying object values properly

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.

Answer №1

Make sure your forEach function includes an argument (such as item) to represent the current element in the item_list array.
Then, within the function, you can access the properties of each item using item.propertyName

<ul>
    <% item_list.forEach(function(item) { %>
    <li>Item Name:<%= item.name %></li>
    <% }); %>
</ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to draw a rectangle outline in Vue.js without the need for any additional packages?

I have been attempting to craft a rectangle outline using vueJS, but so far I have not had much success. I am hoping to achieve this using only CSS, but despite my efforts, I have not been able to find a solution. My goal is to create something similar to ...

Using jQuery to make an AJAX request to a localhost API running on port

I created a RESTful API within a folder named "rest" that connects to port 3000 on my localhost at http://localhost:3000/api/products. Additionally, I developed a jQuery logging application in a folder named "logs" that makes Ajax calls to retrieve data fr ...

When the input field is cleared, JavaScript will not be able to recognize its contents

Having an issue with my function that fetches results, <script language="javascript"> function fetchResult(value){ url="ajax_fetch.php?st=usr&q="+value; ajax(url); } fetchResult(" "); </script&g ...

Dealing with models in Vue.js is proving to be quite a challenge

Why isn't myGame showing as 超級馬力歐 initially and changing when the button is pressed? It just displays {{myGame}} instead. I'm not sure how to fix it, thank you! let myApp = new vue({ el:'myApp', data:{ myGame:&a ...

Encountering a problem when trying to reference socket.io

I've been working on building an express app with chat functionality, but I've run into an issue with socket.io. It's not working properly and is throwing an "uncaught reference" error when I try to run the server. You can see a screenshot o ...

Implementing a sleek show/hide transition using slideToggle in jQuery

Trying to implement show/hide content with slideToggle and it's functioning, but the animation effect on the table is not smooth. Attempted two different codes, but none provided the desired animation effect: $('.more').slideToggle(' ...

Utilizing the EJS access to retrieve express variables within a JavaScript onload function

When working with variables in an EJS file, you can easily access their values. For example: <h1><%= title %></h1> Now, if you want to use the same 'title' variable in an onload JavaScript function on the same EJS page, how wo ...

Having trouble adding items to an array within a Javascript promise

I am facing an issue with the exported function in a Nextjs app, which acts as an API page. The problem arises when the 'domainnames' array returns nothing in the 200 response. Interestingly, if I exclude the 'GetDomainStatus()' funct ...

`In TypeScript Angular, encountering challenges with accessing object properties`

My TypeScript object looks like this const playlist: { tracks: Array<Track> } = { tracks: new Array<Track>() }; This is the Track interface I am working with interface Track { title?: string; album?: string; artists?: string; duration? ...

Utilizing AngularJS: Using ng-click with ng-repeat to retrieve all data simultaneously

Having a simple ng-repeat: <div ng-repeat="x in names"> <h4>{{x.productid}}</h4> <h4>{{x.newquantity}}</h4> <h4>{{x.total}}</h4> <button ng-click="addInfoAboutOrder(x)">Add Info</button> ...

The jQuery function is running double even after I cleared the DOM with the empty() method

Twice, or multiple times if going back and forth, the Jquery function is triggered. Upon loading LoginMenu.jsp, WorkOrder.jsp is loaded within a specified ID. Once WorkOrder.jsp loads, it then loads schedule.jsp in the schedule tab defined in WorkOrders.j ...

Enhancing Vue.js functionality with extra information stored in local storage

I've created a To Do List app where you can add tasks using a button. Each new task is added to the list with a checkbox and delete button in front of it. I'm trying to save all the values from the inputs and the checked checkboxes on the page on ...

Can someone explain the inner workings of the Typescript property decorator?

I was recently exploring Typescript property decorators, and I encountered some unexpected behavior in the following code: function dec(hasRole: boolean) { return function (target: any, propertyName: string) { let val = target[propertyName]; ...

What is the best way to extract a nested array of objects and merge them into the main array?

I've been working on a feature that involves grouping and ungrouping items. A few days ago, I posted this question: How can I group specific items within an object in the same array and delete them from the core array? where some helpful individuals ...

Utilizing SlickGrid and DataView for calculating totals efficiently without the need for grouping

I am attempting to utilize Slick Grid and DataView to calculate column totals similar to the example shown here: . However, I do not want to group my rows. Therefore, I attempted not passing a getter and formatter into the dataView.setGrouping(..) method. ...

Is there a way to utilize jQuery to redirect to the href included in the HTML attachment?

I am looking to add a redirection feature to my website using the href provided in the code by jQuery. This will be done after playing an animation for better user experience. $(document).ready(function(){ $("a").click(function(event){ event.prev ...

Implementing Oauth in Angular and Node

I am facing challenges with implementing oauth in Angular. When I directly enter the link into the browser http://localhost:8080/auth/twitter I am able to successfully connect using oauth and receive a response. However, when I try to achieve the same in ...

Refreshing the Canvas post-submission

I have created a form that allows users to add notes and sign on a Canvas. However, I am facing an issue with clearing the canvas after submission, as it does not seem to work properly. The rest of the form functions correctly. The goal is to clear both t ...

Encountered an error while attempting to access the 'type' property of undefined within the Redux store for an action defined in an external package

In my quest to expand my knowledge of React (coming from an ASP.NET background), I encountered a challenge. I have multiple React applications where I intend to utilize common UI components, so I decided to extract these into a separate npm package. This a ...

Using withRouter() to redirect will display all components

I'm brand new to Reactjs and am currently diving into routing. In my journey, I stumbled upon the use of withRouter() for programmatic redirection. I had assumed the flow would follow: constructor->Willmount->render, but it seems the current or ...