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

147
Visualizações
mongoose populate doesn't work with array of IDs

I have these two 3 models User, Product and Orders and are also has references to each other.

My Orders Schema:

const orderSchema = Schema({

buyerId:{
    type: Schema.Types.ObjectId,
    ref: 'User'
},
totalAmount: {
    type: Number,
    required: [true, "description is required"]
},
    createdOn: {
    type: Date,
    default: new Date()
},
    items:[{type:Schema.Types.ObjectId, ref: 'Product'}]})

I'm trying to use populate() like this:

    Order.find()
    .populate('buyerId')//Reference to User Model
    .populate('items')// Reference to Product Model
    .exec(function (err, result){

        console.log(result);// RETURNS ONLY buyerId populated
        console.log(result.buyerId.name);//Successfully references to my User model and prints name
        console.log(result.items);//Prints Undefined

    })

You can see my console log above and what it returns is only the populated buyerId(only got the reference from my User model)

Seems like my populate('items') doesnt work at all. The items field contains array of IDs, where the IDs are those of products. I need to reference to User and Product both. I'm just following the documentation in mongoose, I don't know what I might be doing wrong.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

use aggregate

Order.aggregate([
    { $match:{ user:"sample_id"
     }
    },
    {$lookup:{
        from:'users', // users collection name
        localField:'buyerId',
        foreignField:'_id',
        as:'buyerId'
    }},
    {
        $lookup:{
            from:'items', //items collection name
            localField:'items',
            foreignField:'_id',
            as:'items'
        }
    },

])
about 4 years ago · Juan Pablo Isaza 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