Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda