1

I am trying to populate a nested object with mongoose. I have a document which contains a list of product or service. I am using refPath to add it dynamically. The problem is when I am trying to populate product/service from path this does not work.

Here my scheme:

const quoteSchema = new Schema({
    other: {type: String},
    list_items: [
    {
        item_id: {
            type: Schema.ObjectId,
            require: true,
            refPath: "type"
        },
        type: {
            type: String,
            required: true,
            enum: ['service', 'product']
        },
        quantity: {type: Number},
        desc: {type: String},
        discount: {type: Number},
        unit_price: {type: Number},
        total: {type: Number},
    }
  ],

});

Then I have my request :

mongoose.model(model).find({ company_id: mongoose.Types.ObjectId(company_id), _id: mongoose.Types.ObjectId(id) })
        .populate([{
          path: 'list_items.item_id',
          model: 'list_items.type'
        }])
        .lean()
        .exec( (err, doc) => {

        return res.json({ success: true, payload: doc });
    });   

1 Answer 1

18

I find the solution ! I modify the refPath by adding array name so it look like

instead of refPath: "onModel"

now is : "list_items.onModel"

Here is the updated schema :

const quoteSchema = new Schema({    
    list_items: [
        {
            item_id: {
                type: Schema.ObjectId,
                require: true,
                refPath: "list_items.onModel"
            },
            onModel: {
                type: String,
                required: true,
                enum: ['service', 'product']
            },
            quantity: {type: Number},
            desc: {type: String},
            discount: {type: Number},
            unit_price: {type: Number},
            total: {type: Number},
            ref: {type: String}
        }
    ],
    })

Then

mongoose.model(model).findOne({ company_id: mongoose.Types.ObjectId(company_id), _id: mongoose.Types.ObjectId(id) })
        .populate('list_items.item_id')
        
        //....

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.