Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

363
Views
nodejs ejs how to display specific field from array of objects in ejs template

I am trying to display a specific field of the first object that is inside a array of objects.

index.js:

router.get('/chatroom', ensureAuthenticated, (req, res) =>  {
const user = req.user
chatroom.find({chatroom_users: user.name},  function (error, data) {  
res.render("chatroom", {
   data,
   user: req.user});
})
}
})

chatroom.ejs:

        <script>
<% for (var i = 0; i < data.length; i++) { %>
var chatroom_message0 =  "<%= data[i].chatroom_message.date%>"
<% } %>


</script>

This is the structure in MongoDB:

enter image description here

But I can only so far show the entire object but not the specific field that I want, in this case the field "date".

enter image description here

I have tried many different combinations for example:

 "<%= data[i].chatroom_message["date"]%>"  
 "<%= data[i].chatroom_message._date%>" 

But I can't get it to work, so any help would be appreciated.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

the date is inside a array so it makes sense that you can't select like that depending on your data format it can be used like this:

   <= data[i].chatroom_message[0].date %>

if the format is

data = [
 {chatroom_message : {date, user_name, message} },
 {chatroom_message : {date, user_name, message} },
]


<% for( let i = 0; i < data.length; i++ ) { %>
  <% const {chatroom_message} = data[i] %> 
  <% for( let j = 0; j < chatroom_message.length; j++ ) { %>
    <%= chatroom_message[j].date %> 
  <% } %>
<% } %>

or if the format is

chatroom_message = [
 {date, user_name, message}
]

<% for( let i = 0; i < chatroom_message.length; i++ ) { %>
  <%= chatroom_message[i].date %> 
<% } %>
about 4 years ago · Juan Pablo Isaza Report

0

I figured it out, I made a typo mistake in my mongodb model I had written "dates"in the model instead of "date" thats why it didn't show up.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!