mongodb 如何在嵌套js中编写数组dto和schema?

vsdwdz23  于 2023-02-11  发布在  Go
关注(0)|答案(1)|浏览(106)
{
    "studentRollNo": 1,
    "firstName": "name",
    "class": "second standard",
    "subjects": [
        {
            "sNo": "1.1",
            "name": "social",
            "marks": "89",
            "questionsAttempted": "100%"
        },
        {
            "sNo": "1.2",
            "name": "mathematics",
            "marks": "69",
            "questionsAttempted": "100%"
        }
    ]
}
juzqafwq

juzqafwq1#

下面是使用mongoose类转换器和swagger的示例方案

@Schema({ timestamps: true })
export class Example {
  @ApiHideProperty()
  @Prop({ type: SchemaTypes.ObjectId, default: Types.ObjectId })
  @Exclude()
  _id: Types.ObjectId;

  @ApiHideProperty()
  @Exclude()
  __v: number;

  @Prop({ type: Number, required: true })
  studentRollNo: number;

  @Prop({ type: String, required: true })
  firstName: string;

  @Prop({ type: String, required: true })
  class: string;

  @Prop(
    raw([
      {
        sNo: { type: Number, required: true },
        name: { type: String, required: true },
        marks: { type: String, required: true },
        questionsAttempted: { type: String, required: true },
      },
    ]),
  )
  subjects: {
    sNo: number;
    name: string;
    marks: string;
    questionsAttempted: string;
  }[];

  @ApiProperty()
  @Expose()
  get id(): string {
    return String(this._id);
  }
}

export const ExampleSchema = SchemaFactory.createForClass(Example);

和DTO

export class SubjectDto {
  sNo: number;

  name: string;

  marks: string;

  questionsAttempted: string;
}

export class ExampleDto {
  studentRollNo: number;

  firstName: string;

  class: string;

  subjects: SubjectDto[];
}

您还可以使用class-validator向这些dto添加验证对于验证“subject”,请在SubjectDto中使用所需的验证,然后将@ValidationNested({each: true})添加到ExampleDto中的subjest字段
如果对您有帮助,请将此答案标记为正确

相关问题