Reputation: 177
I apologize for the poorly worded title, I wasn't sure how to word it properly. So 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: await User.find({"username": Createpost.postUsername})}));
My attempt was to search in the User collection for a matching username field with the postUsername field from the Createpost collection, and then display it in EJS:
<% newPost.forEach(newPost => { %>
Posted by: <%= newPost.postUsername %> - Name: <%= postUser.name %>
<%= newPost.postText %>
<% }%>
But when I do this, nothing appears on the page and I can't figure out any solutions. Any help would be much appreciated.
Edit: I used aggregation like suggested in the comments, but the following just results in text that says [object Object] and I'm not sure why:
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: "postUser"}},{$unset: "postUsername"}])}));
EJS:
<% newPost.forEach(newPost => { %>
Posted by: <%= newPost.postUsername %> - <%= postUser %>
<%= newPost.postText %>
<% }%>
Upvotes: 0
Views: 49
Reputation: 116
Try the aggregate solution: https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/
Createpost.aggregate([
{
$lookup: {
from: "User",
localField: "postUsername",
foreignField: "username",
as: "postUser"
}
},
{
$unset: "postUsername"
},
{
$sort: {date: -1}
}
])
Edit: The output data from the aggregate should be like this:
[{
_id: 60d80b1305dcc535c4bf111a,
postTitle: "test post",
postText: "aaaaa",
//postUsername: "testuser", --> removed cuz its dupplicated with the postUser below!
postUser: {
_id: 60ccb13a21d65f0c7c4c0690,
username: "testuser",
name: "test"
},
// ... more detail of the post
}},...
]
More: Now you can render the ejs with just an array newPost
router.get('/forum', async (req,res)=>res.render('forum', {
newPost: await Createpost.aggregate([
{
$lookup: {
from: "User",
localField: "postUsername",
foreignField: "username",
as: "postUser"
}
},
{
$unset: "postUsername"
},
{
$sort: {data: -1}
}
])
}));
Then parse the newPost array to ejs like below:
<% newPost.forEach(newPost => { %>
Posted by: <%=newPost.postUser.username%> - Name: <%= newPost.postUser.name%>
<%= newPost.postText %>
<% }%>
Upvotes: 1