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

151
Views
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 answers
Answer question

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 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!