简体   繁体   English

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

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

So I'm making a simple forum app and I have 2 collections:所以我正在制作一个简单的论坛应用程序,我有 2 个集合:

User用户

_id:60ccb13a21d65f0c7c4c0690
username: testuser
name: test

And Createpost和创建帖子

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

If I wanted to get data of testuser from User displayed on his forum post, what would be the best way to do that?如果我想从他的论坛帖子上显示的用户那里获取 testuser 的数据,那么最好的方法是什么? This is what I've tried so far:这是我迄今为止尝试过的:

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"}}])}));

Then I want to get the name field from the newly joined documents in EJS like here:然后我想从 EJS 中新加入的文档中获取名称字段,如下所示:

<% newPost.forEach(newPost => { %>
    Posted by: <%= newPost.postUsername %> - Name: <%= postUser.name %>
    <%= newPost.postText %>
<% }%>

But when I do this, it doesn't say anything, or if I only put postUser, it says "[object Object]".但是当我这样做时,它什么也没说,或者如果我只放了 postUser,它会说“[object Object]”。 Any help would be much appreciated.任何帮助将非常感激。

You are missing await in your postUser query.您在postUser查询中缺少await So the return of this query can be a promise .所以这个查询的返回可以是一个promise I edited it a bit and just made 1 query to get all the data you needed.我对其进行了一些编辑,并仅进行了 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 will have a value like this: newPosts将具有如下值:

[{
    "_id" : "60d80b1305dcc535c4bf111a",
    "postTitle" : "test post",
    "postText" : "aaaaa",
    "postUsername" : "testuser",
    "user" : {
        "_id" : ObjectId("60ccb13a21d65f0c7c4c0690"),
        "username" : "testuser",
        "name" : "test"
    }
},...]

Ejs file should be like here: Ejs 文件应该是这样的:

<% newPosts.forEach(newPost => { %>
    Posted by: <%= newPost.postUsername %> - Name: <%= newPost.user.name %>
    <%= newPost.postText %>
<% }%>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM