I'm making a simple forum and want to link two collections so I can display data about the user who made the post on their post:
User.js:
_id:60ccb13a21d65f0c7c4c0690
username: testuser
name: test
And Createpost.js
_id:60d80b1305dcc535c4bf111a
postTitle: "test post"
postText: "aaaaa"
postUsername: "testuser"
I was given advice to try $lookup, so I have this:
router.get('/forum', async (req,res)=>res.render('forum', {
newPost: await Createpost.aggregate([
{
$lookup: {
from: "User",
localField: "postUsername",
foreignField: "username",
as: "postUser"
}
},
{
$sort: {date: -1}
}
])}));
Then I display it in ejs like so:
<% newPost.forEach(newPost => { %>
Posted by: <%= newPost.postUsername %> - Name: <%= newPost.postUser.name %>
<%= newPost.postText %>
<% }%>
All the data from Createpost.js is working fine, postUsername and postText are being displayed, but when it comes to the data I tried to join, like name, it doesn't show anything. I tried console logging the aggregated data, and it looks like postUser is just an empty array so I suspect it's not getting any data from "User"? But I have no idea what I can do, the collection in mongodb is called users rather than User but putting that in the string instead wouldn't work either.
You are writing 'User' as collection name, please check saved collection name in MongoDB. It should be saved as 'users' collection. So, you have to write 'users' in lookup like below code:
router.get('/forum', async (req,res)=>res.render('forum', {
newPost: await Createpost.aggregate([
{
$lookup: {
from: "users",
localField: "postUsername",
foreignField: "username",
as: "postUser"
}
},
{
$sort: {date: -1}
}
])}));