본문 바로가기
Research/Nest.js

nestjs_mongoose 스키마 설계 후 class-validator 적용

by RIEM 2023. 4. 5.

 

스키마 생성

// cats 폴더 내 cats.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, SchemaOptions } from 'mongoose';

const options: SchemaOptions = {
  timestamps: true,
};

@Schema(options)
export class Cat extends Document {
  @Prop({
    required: true,
    unique: true,
  })
  email: string;

  @Prop()
  catname: string;

  @Prop()
  password: string;

  @Prop()
  imgUrl: string;
}

// Cat 클래스를 CatSchema 스키마로 생성
export const CatSchema = SchemaFactory.createForClass(Cat);

같은 cats 모듈 폴더내 cats.schema.ts를 생성해주었다. 

 

Class validator 설치 및 적용

스키마에서 프로퍼티의 데이터 타입을 정의해주었다. 하지만 이와 다른 데이터 타입이 올 경우, 이 타입에 맞게 바꿔줘야 한다. 이를 위해 nestjs의 class validator를 사용하면 된다. https://github.com/typestack/class-validator

$ npm i --save class-validator class-transformer
// cats 폴더 내 cats.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
import { Document, SchemaOptions } from 'mongoose';

const options: SchemaOptions = {
  timestamps: true,
};

@Schema(options)
export class Cat extends Document {
  @Prop({
    required: true,
    unique: true,
  })
  @IsEmail()
  @IsNotEmpty()
  email: string;

  @Prop({
    required: true,
  })
  @IsString()
  @IsNotEmpty()
  name: string;

  @Prop({
    required: true,
  })
  @IsString()
  @IsNotEmpty()
  password: string;

  @Prop()
  @IsString()
  imgUrl: string;
}

// Cat 클래스를 CatSchema 스키마로 생성
export const CatSchema = SchemaFactory.createForClass(Cat);

프로퍼티에 알맞은 class-validator의 데코레이터를 추가했다.

댓글