node.jsexpressmongoosemongoose-populate

Populating Mongoose objects from id to new field


I was working with mongoose to populate field of ids with their respective documents to a new field.my question is assuming my cart model is -

let CartSchema = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    productIds: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Product'
        }
    ]
});

i want to populate the products so i used

Cart.find({}).populate("products").exec(function (err, cart) {
    console.log(cart)
}

but this populates the documents in the same field name productIds and i want to populate those fields in a new field name called "products" so i tried this

let CartSchema = new mongoose.Schema({
        userId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User'
        },
        productIds: [
            {
                type: String
            }
        ]
    }, { toJSON: { virtuals: true } });

CartSchema.virtual('products', {
    ref: 'Product',
    localField: 'productIds',
    foreignField: '_id',
});

Cart.find({}).populate("products").exec(function (err, cart) {
    console.log(cart)
}

but returned empty array named products.so how can i populate the productIds array to a new field name products with their respective document array.

Thanks.


Solution

  • the approch is correct you should see your data poulated in the products field. make sure you have the correct data and model n