Search code examples
arraysjsonmongodbnestjs

how to write dto and schema for array in nest js?


{
    "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%"
        }
    ]
}

Solution

  • Here is an example scheme using mongoose class-transformer and 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);
    

    and DTO

    export class SubjectDto {
      sNo: number;
    
      name: string;
    
      marks: string;
    
      questionsAttempted: string;
    }
    
    export class ExampleDto {
      studentRollNo: number;
    
      firstName: string;
    
      class: string;
    
      subjects: SubjectDto[];
    }
    

    You can also add validation to these dtos using class-validator For validation "subject", use the validation you need in SubjectDto and add @ValidationNested({each: true}) to subjest field in ExampleDto

    Please mark this answer as correct if it helped you