Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda