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!!!
CodePudding user response:
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 %>)
CodePudding user response:
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 %>)