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

98
Visualizações
using mongoose populate to show author

On my site a user can can add a notice, I want the page to show the author of the notice.

const notices = await Notice.findById(id).populate('author');

On this route I can console.log(notices) and see author of the post, and i can show the author using EJS<%= notices.author.username %>

BUUUT on this route

const notices = await Notice.find({}).populate('author');

I can see the authors when i console.log(notices) but when i try to display it with <%= notices.author.username %> i get an error saying username is undefined.

Help!!!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Since notices is an array you should access its elements by index or by mapping its elements:

// Access the first element if present
if (notices.length > 0) {
    <%= notice[0].author.username %>
}

// OR map its elements
notices.map(notice => <%= notice.author.username %>)
about 4 years ago · Juan Pablo Isaza Relatório

0

const notices = await Notice.findById(id).populate('author');   
const notices2 = await Notice.find({}).populate('author');

The above route gets noticed as the object and gets notices2 as the array because of getting notices as the query for findBYID and getting notices2 as the query for the find. That's why getting notices getting object and notices2 getting array.

// notices Object element
<%= notices.author.username %>

//notices2 map elements by display frist authore
if (notices2.length > 0) {
    <%= notices2[0].author.username %>
}
// OR loop for map by display all authore
notices2.map(n => <%= n.author.username %>)
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