Pug模板中嵌套Populate返回JSON格式,如何显示纯用户名?
解决Mongoose嵌套Populate后Pug模板显示用户对象的问题
你遇到的问题是因为comment.user是包含name属性的对象,直接渲染会输出对象的字符串形式,只需修改Pug模板代码,直接访问对象的name属性即可:
修改Pug模板代码
将原代码:
each comment,i in story.comments h6.col-12.comments-text= comment.content | by span.list-all-title= comment.user
替换为:
each comment,i in story.comments h6.col-12.comments-text= comment.content | by span.list-all-title= comment.user.name
可选:处理用户名为空的边界情况
如果担心存在用户未设置名字的情况,可以添加默认值避免页面显示undefined:
each comment,i in story.comments h6.col-12.comments-text= comment.content | by span.list-all-title= comment.user.name || '匿名用户'
你的Mongoose查询已经通过select: {"name":1, _id: 0}正确只返回了用户的name字段,无需修改后端查询逻辑,仅调整前端模板即可解决问题。
内容的提问来源于stack exchange,提问作者aksit
相关产品推荐
相关产品推荐

