使用猫鼬填充显示作者

using mongoose populate to show author

在我的网站上,用户可以添加通知,我希望页面显示通知的作者。

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

在这条路线上,我可以 console.log(通知)并看到 post 的作者,并且我可以使用 EJS<%= notices.author.username %>[=12 向作者展示=]

这条路线上的 BUUUT

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

当我 console.log(通知)时我可以看到作者,但是当我尝试用 <%= notices.author.username %> 显示它时,我收到一条错误消息,提示用户名未定义。

求助!!!

由于 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 %>)
const notices = await Notice.findById(id).populate('author');   
const notices2 = await Notice.find({}).populate('author');

上面的路由作为对象得到通知,并作为数组得到通知,因为得到通知作为查询 findBYID 和得到通知 2 作为查找的查询。 这就是为什么 getting 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 %>)