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

Exploring the bounds of self-invocation functions in JavaScript

Have you ever wondered why self-invocation functions inside another function in JavaScript don't inherit the scope of the outer function? var prop = "global"; var hash = { prop: "hash prop", foo: function(){ console.log(this.prop); ...

What is the proper usage of main.js and main.css within the skeleton portlet project that is created by the Liferay 6.0.6 plugin SDK?

Is it a good practice to include portlet-specific JS or CSS in them only if <portlet:namespace /> works within them? Should I rely on unique function/variable names or class names instead? ...

Attempting to transform a numerical value into CSS syntax

Currently, I am attempting to loop through several DIV elements, extract a numerical value from each DIV, and then based on that value matching a specific value in the JavaScript code, assign a particular CSS Class back to the original DIV. This is the sn ...

"Observed Issue: Ionic2 Array Fails to Update in HTML Display

I am struggling with updating an array in Ionic2 and Angular2. I have tried updating it on the front end but it's not working, even though it updates perfectly on the backend (ts) as confirmed by checking the console. I need assistance with this. Her ...

The versatility of Node.js' hbs module as an engine

Recently diving into the world of node js, I stumbled upon the hbs module. In this code snippet below: app.set('view engine', 'html'); app.engine('html', require('hbs').__express); I'm curious to know more abo ...

The success function in AJax does not properly execute on Safari browsers

Here is an example of my AJAX function: $.ajax({ url: "thankyou", type: "POST", data: arr, tryCount : 0, retryLimit : 3, success: function(response) { if(response == "Success"){ location.href = "/thankyou.html"; }else{console.l ...

Can anyone assist with troubleshooting the font size issue for a JavaScript tooltip on Joomla 1.5 with CK Forms?

My Joomla 1.5 site has CK Forms installed and is functioning properly, except for one issue: the tooltip on the captcha is not displaying correctly. It appears in a tiny 1px font size. Even though I have tried debugging using Firebug and confirmed that the ...

Guide on performing integration tests on API endpoints in the 'api/:id' format with mocha and supertest

Currently, I am facing some challenges with integration testing an API endpoint that is supposed to return specific user data by attaching the userId to the endpoint. While I can successfully test the endpoint that returns all users, I encounter issues wh ...

Reinitializing the database with Cypress (postgresql)

When populating the database, I intentionally do it partially for certain tests. However, after completing all tests, I would like to reset the database in order to avoid any complications that may arise during the next populate process. How can I efficien ...

"Managing the flow: Throttling streams in Node

Currently, I am in the process of developing a Node.js HTTP file streaming server with specific requirements: sender --HTTP POST--> Node.js HTTP Server <--HTTP GET-- receiver I have successfully implemented this functionality using the following co ...

Error: foobar is not defined within this scope (anonymous function)

I'm facing an issue with a JavaScript file hosted on a domain called foobar.com. at http://foobar.com/static/js/main.js: $(document).ready(function() { function foobar(bar){ $.ajax({ url: "/site/foo/", ...

What is the best way to incorporate parallax scrolling in the center of a webpage?

I am trying to implement a parallax scrolling effect in the middle of my page, but it seems to be causing issues once I reach that section while scrolling. I attempted to use intersection observer, but unfortunately, it did not resolve the problem. const ...

What is the best way to group a Pie Chart by a string field in a .csv file using dc.js, d3.js, and crossfilter.js in a Node environment?

I've successfully set up several Dimensions and groups, but I'm encountering an issue with a Pie Chart that needs to be grouped based on domain names like bing.com. Each domain name is parsed consistently to xxxx.xxx format and the data is clean. ...

Issue encountered with Express.js and connect-mongo session: "TypeError - Unable to access property 'upserted' as it is undefined"

I'm working on implementing session storage using the connect-mongo module, but I keep encountering the following error: TypeError: Cannot read property 'upserted' of undefined Here is how I'm using the connect-mongo: import session ...

What is the best way to redirect to a specific page when logging out of a website?

To begin, let me outline the situation at hand. We have two distinct websites - website-A and website-B. Each of these websites is hosted on separate domains. A user has the ability to log in to website-B's homepage through the login page of webs ...

The Material UI Menu does not close completely when subitems are selected

I am working on implementing a Material UI menu component with custom MenuItems. My goal is to enable the closure of the entire menu when clicking outside of it, even if a submenu is open. Currently, I find that I need to click twice – once to close the ...

Unable to send multiple cookies using custom headers in Next.js configuration

I am using custom headers to set the cookie in my next.config.js file. The refresh token is successfully set, but for some reason the second token is not being recognized. key: 'Set-Cookie', value: `RefreshTokenKey = " ...

Utilizing jQuery to fetch the source value of an image when the closest radio button is selected

On my website, I have a collection of divs that display color swatches in thumbnail size images. What I want to achieve is updating the main product image when a user clicks on a radio button by fetching the source value of the image inside the label eleme ...

Validating form field values in JavaScript prior to submission

My website features a search box that allows users to search through a database of books. When utilizing the search feature, users are presented with the following options: Search Query (a text input field) Where to search (a select field with the option ...

Finding the measurement of a sofa using couch.get(data, headers, status)

After attempting to set up a node.js application with express.js by connecting to couchdb, I utilized the npm package called nodejs-couch. app.get('/', function(req, res) { couch .get(dbName, viewUrl) .then( function(data, heade ...