![](/img/trans.png)
[英]Trying to display image or any type of data dynamically in my ejs template to get from mongodb collections
[英]How to get the aggregated data from mongodb to display in ejs?
所以我正在制作一个简单的论坛应用程序,我有 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]”。 任何帮助将非常感激。
您在postUser
查询中缺少await
。 所以这个查询的返回可以是一个promise
。 我对其进行了一些编辑,并仅进行了 1 次查询以获取您需要的所有数据。
router.get('/forum', async (req, res) => {
const newPosts = await Createpost.aggregate([
{
$lookup: {
from: 'users',
localField: 'postUsername',
foreignField: 'username',
as: 'user'
}
},
{
$unwind: '$user'
}
]);
res.render('forum', {
newPosts
});
});
newPosts
将具有如下值:
[{
"_id" : "60d80b1305dcc535c4bf111a",
"postTitle" : "test post",
"postText" : "aaaaa",
"postUsername" : "testuser",
"user" : {
"_id" : ObjectId("60ccb13a21d65f0c7c4c0690"),
"username" : "testuser",
"name" : "test"
}
},...]
Ejs 文件应该是这样的:
<% newPosts.forEach(newPost => { %>
Posted by: <%= newPost.postUsername %> - Name: <%= newPost.user.name %>
<%= newPost.postText %>
<% }%>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.