【问题标题】:How to get the aggregated data from mongodb to display in ejs?如何从 mongodb 获取聚合数据以显示在 ejs 中?
【发布时间】: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


    【解决方案1】:

    您的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 %>
    <% }%>
    

    【讨论】:

    • 您好,感谢您的帮助!我尝试了您的解决方案,它显示了来自 Createpost 的数据,而不是来自用户的数据。我怀疑这是“来自:”参数或我尝试使用 newPost.user.name 检索数据的方式的问题,但我不确定。我的用户模式在 VS 代码中称为 User.js,但在 mongodb 中它显示“用户”,这可能是个问题吗?
    • 我已经改变了我的答案。 from 的值是 mongodb (users) 中的集合名称,而不是架构文件名。请改用from: 'users'。希望它对你有用。
    • 哈哈哈,我昨天想通了,但我花了大约 5 个小时......我觉得很愚蠢,但谢谢你的帮助:D
    猜你喜欢
    • 2021-05-21
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 2021-02-08
    • 2023-01-14
    • 2017-05-10
    • 1970-01-01
    • 2021-07-01
    相关资源
    最近更新 更多