Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

198
Views
Foreign collection doesn't seem to be appearing in aggregated data

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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}
    }  
    ])}));
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!