스키마 생성
// 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의 데코레이터를 추가했다.
'Research > Nest.js' 카테고리의 다른 글
nestjs_signup api 구현 + virtual 필드로 민감정보는 숨기기 (0) | 2023.04.05 |
---|---|
nestjs_DTO 만들고 붙이기 (0) | 2023.04.05 |
nestjs_배포 환경에 따른 mongoDB 로깅 설정 (0) | 2023.04.05 |
nestjs_환경변수 설정 +mongodb 연동 (0) | 2023.04.05 |
nestjs_횡적 부가기능을 위한 interceptor (0) | 2023.04.04 |
댓글