简体   繁体   中英

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:

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? 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:

<% 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]". Any help would be much appreciated.

You are missing await in your postUser query. So the return of this query can be a promise . I edited it a bit and just made 1 query to get all the data you needed.

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:

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

Ejs file should be like here:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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