【问题标题】:how to reference nested documents in nestjs mongoose typescript如何在nestjs mongoose typescript中引用嵌套文档
【发布时间】:2021-07-20 15:01:00
【问题描述】:

我是 nestjs 的新手。我使用@nestjs/mongoose,我需要在我的类模式中引用嵌套对象中的几个字段,但我不知道该怎么做。

dietDays 对象必须包含一个日期字段和餐点对象,其中包含对 Meal 架构的 2 个引用。

正确的做法是什么?

下面的代码显示了我是如何尝试这样做的,以及我尝试的另一种方法是创建 dietDays 类并将其传递给 Prop 类型变量,但在那种情况下我无法引用 @987654325 @schema,因为那不是架构。

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

【问题讨论】:

    标签: mongoose nestjs nestjs-mongoose


    【解决方案1】:

    你应该这样做:

    创建一个类,它指的是饮食中的每一天(逻辑上有意义)

    @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' }
      ]
    }
    

    【讨论】:

    • 感谢您的回答,但我对应该包含饮食日数组的饮食模式有点困惑(根据您的回答 DayInDiet)。如何在我的饮食模式中使用 DayInDiet 模式?再次感谢:))
    • @soheib 我已经根据最终的Diet schema 编辑了答案
    猜你喜欢
    • 2018-11-09
    • 2020-10-04
    • 2016-04-25
    • 2021-08-22
    • 2012-04-16
    • 2020-05-02
    • 2017-04-01
    • 2014-08-05
    • 1970-01-01
    相关资源
    最近更新 更多