NestJS MongoDB 사용하기3- DB Create Read

 안녕하세요. 알렉스입니다. 저번 포스팅에 이어 이번에는 MongoDB에 CRUD기능을 넣도록 하겠습니다. 처음 들어오셨다면 이전글을 참고해 주시기 바랍니다.


이전글 : NestJS MongoDB 사용하기2 - DB 스키마 생성


// src/users/dto/create-user.dto.ts
import { ApiProperty } from '@nestjs/swagger';
import {
IsInt,
IsNotEmpty,
IsObject,
IsOptional,
IsString,
Max,
Min,
} from 'class-validator';

export class CreateUserDto {
@IsString()
@IsNotEmpty()
@ApiProperty({
description: '유저 고유ID',
type: String,
example: 'abc123',
})
id: string;

@IsString()
@IsNotEmpty()
@ApiProperty({
description: '유저 이름',
type: String,
example: 'alex',
})
name: string;

@IsString()
@IsNotEmpty()
@ApiProperty({
description: '유저 전화번호',
type: String,
example: '01035451268',
})
mobile: string;

@IsInt()
@Min(20)
@Max(99)
@IsNotEmpty()
@ApiProperty({
description: '유저 나이(가입 가능나이 20 ~ 99세)',
type: Number,
example: 30,
})
age: number;

@IsString({ each: true })
@IsOptional()
@ApiProperty({
description: '취미 입력(배열)',
type: Array,
example: ['자전거', '수영', '암벽등반'],
})
hobby: string[];

@IsOptional()
@IsObject()
@ApiProperty({
description: '유저의 기타사항 입력',
type: Object,
example: {
character: '성격 좋음',
girlfriend: {
Jain: {
age: 20,
height: 175,
address: 'seoul',
},
Jasmine: {
age: 19,
height: 170,
address: 'busan',
},
},
cars: {
Lamborghini: {
Miura: {
amount: 2,
color: ['black', 'white'],
},
},
},
},
})
etc: object;
}

코드1) create user dto 작성


// src/users/users.controller.ts
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Query,
} from '@nestjs/common';
import { ApiOperation, ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { UsersService } from './users.service';

@ApiTags('users Api')
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}

@Post()
@ApiOperation({
summary: '유저를 생성한다',
description: 'MongoDB에 저장할 유저를 생성한다',
})
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}

@Get()
@ApiOperation({
summary: '전체 조회',
description:
'skip, take을 이용하여 MongoDB의 컬렉션 내에 있는 Documents를 조회한다.',
})
@ApiQuery({
name: 'skip',
type: Number,
example: 0,
})
@ApiQuery({
name: 'take',
type: Number,
example: 0,
})
async findAll(@Query('skip') skip: number, @Query('take') take: number) {
return await this.usersService.findAll(skip, take);
}

@Get(':id')
@ApiOperation({
summary: '한개의 Document 조회',
description: 'id를 이용하여 한개의 Document를 조회한다.',
})
@ApiParam({
name: 'id',
type: String,
example: 'abc123',
})
async findOne(@Param('id') id: string) {
return await this.usersService.findOne(id);
}

@Patch(':id')
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
return this.usersService.update(+id, updateUserDto);
}

@Delete(':id')
remove(@Param('id') id: string) {
return this.usersService.remove(+id);
}
}

코드2) users.controller.ts 작성


// src/users/users.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import mongoose from 'mongoose';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { Users } from './schemas/user.schemas';

@Injectable()
export class UsersService {
constructor(
// // User모델을 UsersService Class에 넣어준다.
@InjectModel(Users.name)
private userModel: mongoose.Model<Users>,
) {}

// 유저 생성
async create(createUserDto: CreateUserDto) {
const createUser = await this.userModel.create(createUserDto);
return await createUser.save();
}

// skip, take을 이용하여 유저 나열하기 createdAt기존으로 DESC
async findAll(skip: number, take: number) {
const result = await this.userModel
.find({})
.sort({ createdAt: -1 }) // 최신날짜가 0번 인덱스로 올라오도록 설정 (-1 :DESC, 1:ASD)
.skip(skip)
.limit(take);
return result;
}

// id를 이용하여 하나의 유저 찾기
async findOne(id: string) {
const result = await this.userModel.find({ id });
console.log('findOne : ', result);
return result[0] ? result[0] : false;
}

update(id: number, updateUserDto: UpdateUserDto) {
return `This action updates a #${id} user`;
}

remove(id: number) {
return `This action removes a #${id} user`;
}
}

코드3) users.service.ts작성


코드1,2,3을 모두 작성하고 NestJS을 실행하면 아래와 같이 Swagger에서 Create, Read를 할수 있는것을 확인할수 있습니다.



사진1) 유저 생성



사진2) MongoDB의 생성 결과


사진3) skip, take을 이용한 전체 조회

사진3과 같이 조회할 경우 document의 생성날짜에 따라 배열로 출력하게 됩니다.


다음은 Update, Delete을 진행하도록 하겠습니다.

다음글 : NestJS MongoDB 사용하기4- DB Update Delete



댓글

이 블로그의 인기 게시물

Lesson 12_1 프로퍼티 노드(Property Node)

DAQ로 전압 측정하기-2

Lesson 12_2 참조를 이용한 프로퍼티노드(Property Node)