[英]Getting data of a user that matches the user who created a post
我為標題措辭不當而道歉,我不知道如何正確地措辭。 所以我有 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: await User.find({"username": Createpost.postUsername})}));
我的嘗試是在 User 集合中搜索與 Createpost 集合中的 postUsername 字段匹配的用戶名字段,然后在 EJS 中顯示它:
<% newPost.forEach(newPost => { %>
Posted by: <%= newPost.postUsername %> - Name: <%= postUser.name %>
<%= newPost.postText %>
<% }%>
但是當我這樣做時,頁面上什么也沒有出現,我想不出任何解決方案。 任何幫助將非常感激。
編輯:我使用了評論中建議的聚合,但以下只會導致顯示 [object Object] 的文本,我不確定為什么:
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: "postUser"}},{$unset: "postUsername"}])}));
EJS:
<% newPost.forEach(newPost => { %>
Posted by: <%= newPost.postUsername %> - <%= postUser %>
<%= newPost.postText %>
<% }%>
嘗試聚合解決方案: https : //docs.mongodb.com/manual/reference/method/db.collection.aggregate/
Createpost.aggregate([
{
$lookup: {
from: "User",
localField: "postUsername",
foreignField: "username",
as: "postUser"
}
},
{
$unset: "postUsername"
},
{
$sort: {date: -1}
}
])
編輯:聚合的輸出數據應該是這樣的:
[{
_id: 60d80b1305dcc535c4bf111a,
postTitle: "test post",
postText: "aaaaa",
//postUsername: "testuser", --> removed cuz its dupplicated with the postUser below!
postUser: {
_id: 60ccb13a21d65f0c7c4c0690,
username: "testuser",
name: "test"
},
// ... more detail of the post
}},...
]
更多:現在你可以只用一個數組 newPost 來渲染 ejs
router.get('/forum', async (req,res)=>res.render('forum', {
newPost: await Createpost.aggregate([
{
$lookup: {
from: "User",
localField: "postUsername",
foreignField: "username",
as: "postUser"
}
},
{
$unset: "postUsername"
},
{
$sort: {data: -1}
}
])
}));
然后將 newPost 數組解析為 ejs,如下所示:
<% newPost.forEach(newPost => { %>
Posted by: <%=newPost.postUser.username%> - Name: <%= newPost.postUser.name%>
<%= newPost.postText %>
<% }%>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.