填充数组 refPath 嵌套对象

Nic*_*cks 1 mongoose express

我正在尝试用猫鼬填充嵌套对象。我有一份包含产品或服务列表的文档。我正在使用 refPath 动态添加它。问题是当我尝试从路径填充产品/服务时,这不起作用。

这是我的计划:

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

});
Run Code Online (Sandbox Code Playgroud)

然后我有我的要求:

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 });
    });   
Run Code Online (Sandbox Code Playgroud)

Nic*_*cks 12

我找到了解决方案!我通过添加数组名称来修改 refPath,使其看起来像

而不是 refPath:“onModel”

现在是:“list_items.onModel”

这是更新后的架构:

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}
        }
    ],
    })
Run Code Online (Sandbox Code Playgroud)

然后

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