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

94
Views
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 answers
Answer question

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 Report

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 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!