在我的網站上,用戶可以添加通知,我希望頁面顯示通知的作者。
const notices = await Notice.findById(id).populate('author');
在這條路線上,我可以 console.log(notices) 并查看帖子的作者,我可以使用 EJS<%= notices.author.username %> 向作者展示
BUUUT 在這條路線上
const notices = await Notice.find({}).populate('author');
當我使用 console.log(notices) 時,我可以看到作者,但是當我嘗試使用 <%= notices.author.username %> 顯示它時,我收到一條錯誤訊息,提示用戶名未定義。
幫助!!!
uj5u.com熱心網友回復:
由于notices是一個陣列,您應該通過索引或映射其元素來訪問其元素:
// Access the first element if present
if (notices.length > 0) {
<%= notice[0].author.username %>
}
// OR map its elements
notices.map(notice => <%= notice.author.username %>)
uj5u.com熱心網友回復:
const notices = await Notice.findById(id).populate('author');
const notices2 = await Notice.find({}).populate('author');
上面的路由作為物件被注意到,并作為陣列得到 notices2,因為將 notices 作為 findBYID 的查詢并將 notices2 作為 find 的查詢。這就是為什么讓 notices 獲得物件和 notices2 獲得陣列的原因。
// 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 %>)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/436969.html
標籤:javascript 节点.js 表示 猫鼬 ejs
