NestJS의 스키마 기본 개념

스키마

몽구스의 모든 것은 스키마에서 파생된다. 각 스키마는 몽고디비 컬렉션에 매핑되고 해당 컬렉션 내의 문서 모양을 정의한다. 스키마는 모델을 정의하는 데 사용되는데, 모델이란 몽고디비 데이터베이스에서 문서를 만들고 읽는 역할을 한다. 스키마를 만들 때에는 @Schma() 데코레이터를 사용한다.

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, SchemaOptions } from 'mongoose';

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

@Schema(options)
export class Cat extends Document {   // 몽구스의 Document를 상속받음

export const CatSchema = SchemaFactory.createForClass(Cat);

위 코드는 cat.schma 파일에 스키마를 데코레이터로 정의한 것이다. Cat이라는 클래스는 SchemaFactory.createForClass를 통해 CatSchema라는 이름의 스키마가 된다. options는 스키마에 대한 옵션인데 timestamps 옵션은 만들어진 시간과 업데이트된 시간을 찍어 준다.


💫 스키마의 컬럼

스키마의 컬럼은 각각의 @Prop으로 정의할 수 있다. 그리고 추가적인 옵션을 설정해 준다. 이를 통해 반드시 필요한 속성인지 여부를 나타내거나 기본값을 지정하거나 할 수 있다. 아래의 컬럼들 중 email, catname, password는 required 속성이 true가 된다. 이미지의 required 값은 false이므로 생략할 수 있다. (기본값이 false이다)

⁝
@Schema(options)
export class Cat extends Document {   // 몽구스의 Document를 상속받음
  @Prop({
        required: true,
        unique: true,
  })
  email: string;

  @Prop({
        required: true,
  })
  catname: number;

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

 @Prop()
  imgUrl: string;
}

export const CatSchema = SchemaFactory.createForClass(Cat);

💫 class-validation

이제 컬럼에 validation을 추가해 줄 차례다. 예를 들어 이메일이 디비에 저장될 때 이메일의 형식이 아닌 경우를 막기 위해 validation을 해 주는 것이다. 이를 위해 라이브러리를 하나 더 설치하자. npm i --save class-validator class-transformer으로 설치 가능하다. class validator의 자세한 사용법은 여기에서 확인할 수 있다.

⁝
@Schema(options)
export class Cat extends Document {   // 몽구스의 Document를 상속받음
  @Prop({
        required: true,
        unique: true,
  })
  @IsEmail()
  @IsNotEmpty()
  email: string;

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

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

 @Prop()
  imgUrl: string;
}

export const CatSchema = SchemaFactory.createForClass(Cat);

사용된@IsEmail(), @IsNotEmpty(), @IsString() 데코레이터들이 validator다.

이제 class validation의 원활한 사용을 위해 main 파일에서 app.useGlobalPipes(new ValidationPipe());로 등록까지 마치면 스키마 설계가 끝난다. 💁🏻‍♀️

좋은 웹페이지 즐겨찾기