728x90
반응형

지난글에 이어서 PATCH와 DELETE를 구현해보자.

 

먼저 npm 모듈을 설치하고 UpdateCatDto를 만들어준다.

 

$ npm i @nestjs/mapped-types

 

update-cat.dto.ts

import {IsString, IsNumber} from 'class-validator'
import { PartialType } from '@nestjs/mapped-types';
import { CreateCatDto } from './create-cat.dto';

export class UpdateCatDto extends PartialType(CreateCatDto) {}

 

Update 먼저 구현해보자.  컨트롤러와 서비스를 바꿔준다.

 

cats.controller.ts

import { Controller, Get, Param, Post, Delete, Patch, Body, Query } from '@nestjs/common';
import { CatsService } from './cats.service';
import { CreateCatDto } from './dto/create-cat.dto';
import { UpdateCatDto } from './dto/update-cat.dto';
import { Cat } from './schemas/cat.schema';


@Controller('cats')
export class CatsController {
    constructor(private readonly catsService: CatsService) {}

    @Get()
    async getAll(): Promise<Cat[]> {
        return await this.catsService.getAll();
    }

    @Get('/:id')
    async getOne(@Param('id') catId: number): Promise<Cat[]> {
        console.log(catId)
        return await this.catsService.getOne(catId);
    }

    @Post()
    async create(@Body() catsData : CreateCatDto) {
        return await this.catsService.create(catsData);
    }

    @Patch('/:id')
    async update(@Param('id') catId: number, @Body() updateData: UpdateCatDto) {
        return this.catsService.update(catId,updateData)
    }

}

 

cats.service.ts

import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Cat, CatDocument } from './schemas/cat.schema';
import { CreateCatDto } from './dto/create-cat.dto';
import { UpdateCatDto } from './dto/update-cat.dto';

@Injectable()
export class CatsService {
  constructor(@InjectModel(Cat.name) private catModel: Model<CatDocument>) {}

  async getAll(): Promise<Cat[]> {
    return await this.catModel.find().exec();
  }

  async getOne(id:number): Promise<Cat[]> {
    return await this.catModel.find({"id" : id});
  } 

  async create(catsData: CreateCatDto) {
    let latestId = await this.catModel.findOne();
    return await this.catModel.create({...catsData, id : parseInt(latestId ? latestId.id : 0)+1});
  }

  async update(id: number, updateData : UpdateCatDto) {
    try {
      await this.catModel.where({"id" : id}).update(updateData);
      return true
    }
    catch(e) {
      return false
    }
  }
}

PATCH 메소드로 요청을 보내보자.


 GetAll()로 확인해보자.

 

정상적으로 id가 1인 데이터의 name이 "초코"로 바뀐 것을 확인할 수 있다.

 

 

DELETE도 만들어보자.

 

cats.controller.ts

import { Controller, Get, Param, Post, Delete, Patch, Body, Query } from '@nestjs/common';
import { CatsService } from './cats.service';
import { CreateCatDto } from './dto/create-cat.dto';
import { UpdateCatDto } from './dto/update-cat.dto';
import { Cat } from './schemas/cat.schema';


@Controller('cats')
export class CatsController {
    constructor(private readonly catsService: CatsService) {}

    @Get()
    async getAll(): Promise<Cat[]> {
        return await this.catsService.getAll();
    }

    @Get('/:id')
    async getOne(@Param('id') catId: number): Promise<Cat[]> {
        console.log(catId)
        return await this.catsService.getOne(catId);
    }

    @Post()
    async create(@Body() catsData : CreateCatDto) {
        return await this.catsService.create(catsData);
    }

    @Patch('/:id')
    async update(@Param('id') catId: number, @Body() updateData: UpdateCatDto) {
        return this.catsService.update(catId,updateData)
    }

    @Delete('/:id')
    async delete(@Param('id') catId: number) {
        return this.catsService.delete(catId);
    }

}

 

cats.service.ts

import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Cat, CatDocument } from './schemas/cat.schema';
import { CreateCatDto } from './dto/create-cat.dto';
import { UpdateCatDto } from './dto/update-cat.dto';

@Injectable()
export class CatsService {
  constructor(@InjectModel(Cat.name) private catModel: Model<CatDocument>) {}

  async getAll(): Promise<Cat[]> {
    return await this.catModel.find().exec();
  }

  async getOne(id:number): Promise<Cat[]> {
    return await this.catModel.find({"id" : id});
  } 

  async create(catsData: CreateCatDto) {
    let latestId = await this.catModel.findOne();
    return await this.catModel.create({...catsData, id : parseInt(latestId ? latestId.id : 0)+1});
  }

  async update(id: number, updateData : UpdateCatDto) {
    try {
      await this.catModel.where({"id" : id}).update(updateData);
      return true
    }
    catch(e) {
      return false
    }
  }

  async delete(id: number) {
    try {
      await this.catModel.remove({"id" : id});
      return true
    }
    catch(e) {
      return false
    }
  }
}

 


postman으로 실행해본다.


getAll() 전체데이터를 확인해본다.

 

 

이렇게 몽고DB로 연결해서 데이터 CRUD 하는 것을 완성하였다.

728x90
반응형

'Back-End > Nest.js' 카테고리의 다른 글

Nest.js | Middleware  (0) 2021.10.28
Nest.js | Swagger  (0) 2021.10.28
Nest.js | MongoDB | Create  (0) 2021.10.06
Nest.js | MongoDB | Find  (0) 2021.10.06
Nest.js | MongoDB | Model,Schema,Controller  (0) 2021.10.06

+ Recent posts