Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

364
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda