Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

365
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda