【发布时间】:2021-06-30 13:48:21
【问题描述】:
所以我正在制作一个简单的论坛应用程序,我有 2 个收藏:
用户
_id:60ccb13a21d65f0c7c4c0690
username: testuser
name: test
然后创建帖子
_id:60d80b1305dcc535c4bf111a
postTitle: "test post"
postText: "aaaaa"
postUsername: "testuser"
如果我想从他的论坛帖子中显示的用户那里获取 testuser 的数据,那么最好的方法是什么?这是我迄今为止尝试过的:
router.get('/forum', async (req,res)=>res.render('forum', {newPost: await Createpost.find().sort({ date: 'desc'}),
postUser: Createpost.aggregate([{$lookup: { from: "User", localField: "postUsername", foreignField: "username", as: "user"}}])}));
然后我想从 EJS 中新加入的文档中获取名称字段,如下所示:
<% newPost.forEach(newPost => { %>
Posted by: <%= newPost.postUsername %> - Name: <%= postUser.name %>
<%= newPost.postText %>
<% }%>
但是当我这样做时,它什么也没说,或者如果我只输入 postUser,它会说“[object Object]”。任何帮助将不胜感激。
【问题讨论】:
标签: javascript node.js mongodb express ejs