Home > Back-end >  mongoose populate doesn't work with array of IDs
mongoose populate doesn't work with array of IDs

Time:09-17

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.

CodePudding user response:

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'
        }
    },

])
  • Related