如何在nestjs mongoose typescript中引用嵌套文档



我是nestjs的新手。我使用@nestjs/mongoose,我需要引用类模式中嵌套对象中的几个字段,但我不知道如何做到这一点

dietDays对象必须包含一个日期字段和包含对Meal模式的2个引用的膳食对象。

正确的方法是什么?

下面的代码显示了我是如何做到这一点的,我尝试的另一种方法是创建dietDays类并将其传递给Prop类型变量,但在这种情况下,我无法引用Meal模式,因为它不是模式。

@Schema()
export class Diet {
@Prop({ default: ObjectID })
_id: ObjectID 
@Prop()
dietDays: [
{
date: string
meals: {
breakfast: { type: Types.ObjectId; ref: 'Meal' }
lunch: { type: Types.ObjectId; ref: 'Meal' }
}
},
]
}

您应该按照以下步骤操作:

创建一个涉及饮食中每一天的类(从逻辑上讲是有意义的(

@Schema()
export class DayInDiet {
@Prop() date: string;
@Prop()
meals:
{
breakfast: { type: Types.ObjectId, ref: 'breakfast' }
launch: { type: Types.ObjectId, ref: 'launch' }
}
}

知道breakfastlunch中的每一个都应该是有效的mongo模式。

如果breakfastlunch不是模式,并且您有一个内容列表,则可以在模式对象内传递此数组作为它们的可能选项。

的另一种可能方式

@Schema()
export class DayInDiet {
@Prop() date: string;
@Prop()
meals: [
{ type: Types.ObjectId, ref: 'meal' } // note that meal should be the name of your schema
]
}
@Schema()
export class Meal {
@Prop() name: string;
@Prop() type: 'launch' | 'breakfast'
}

请注意,您不需要将_id作为任何模式的道具

编辑

对于饮食模式

@Schema()
export class Diet {
// list of props
// ...
@Prop()
dietDays: [
{ type: Types.ObjectId, ref: 'DayInDiet' }
]
}

最新更新