如何从 mongodb 中获取聚合数据以显示在 ejs 中?

How to get the aggregated data from mongodb to display in ejs?

所以我正在制作一个简单的论坛应用程序并且我有 2 个集合:

用户

_id:60ccb13a21d65f0c7c4c0690
username: testuser
name: test

并创建post

_id:60d80b1305dcc535c4bf111a
postTitle: "test post"
postText: "aaaaa"
postUsername: "testuser"

如果我想从他的论坛 post 上显示的用户那里获取 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。所以这个查询的 return 可以是 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 %>
<% }%>