Home > Mobile >  nodejs ejs how to display specific field from array of objects in ejs template
nodejs ejs how to display specific field from array of objects in ejs template

Time:03-24

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.

CodePudding user response:

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 %> 
<% } %>

CodePudding user response:

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.

  • Related