Given the following code:
@openapi.definition({ title: 'Discount', hidden: configOpenapi.internalEndpointsHidden })
@mgoose.schema({ _id: false })
export class Discount {
@mgoose.prop({ required: true, type: Schema.Types.ObjectId, ref: 'DiscountProfile' })
@openapi.prop({ required: true })
discountProfileId?: string;
}
@openapi.definition({ title: 'BrandCreationRequest', hidden: configOpenapi.internalEndpointsHidden })
export class BrandCreationRequest {
@openapi.prop({ required: true })
_id: string;
@mgoose.prop({ required: false, type: [Discount], default: [] })
@openapi.prop({ required: false, default: [], type: 'array' })
discounts?: Discount[];
}
Currently it is not possible to create a virtual property using the @mgoose.populate decorator. Tried several options:
- Using populate decorator directly in the property
- Using virtual decorator creating a property in the Discounts class.
These options doesn't work either if I add the virtual by code to the Discounts, so it's probably a mongoose limitation.
@mgoose.prop({ required: true, type: Schema.Types.ObjectId, ref: 'DiscountProfile' })
@mgoose.populate({
name: 'discountProfile',
opts: { ref: 'DiscountProfile', foreignField: '_id', justOne: true },
})
@openapi.prop({ required: true })
discountProfileId?: string;
@mgoose.virtual({ ref: 'DiscountProfile', localField: 'discountProfileId', foreignField: '_id', justOne: true })
discountProfile?: DiscountProfileSchema;
- Using virtual decorator directly in the parent
In this case there is a collision between properties
@mgoose.prop({ required: false, type: [Discount], default: [] })
@openapi.prop({ required: false, default: [], type: 'array' })
@mgoose.virtual({ ref: 'DiscountProfile', localField: 'discounts.discountProfileId', foreignField: '_id', justOne: true })
discounts?: Discount[];
- Using populate decorator directly in the property
This might work, but the localField is override internally in the decorator (it is not an input option)
@mgoose.prop({ required: false, type: [Discount], default: [] })
@openapi.prop({ required: false, default: [], type: 'array' })
@mgoose.populate({
name: 'discounts.discountProfile',
opts: { ref: 'DiscountProfile', foreignField: '_id', localField: 'discounts.discountProfile', justOne: true },
})
discounts?: Discount[];
Doing in this way by code it works:
schema.virtual('discounts.discountProfile', {
ref: 'DiscountProfile',
localField: 'discounts.discountProfileId',
foreignField: '_id',
justOne: true,
});
So an option would be to add the localField as an input of the @mgoose.populate decorator but we should make sure current code is not using it or could have undesired consequences.
As reference, mongoose discussion about this