끄적이는 개발노트

NestJS와 MongoDB 연결하기(3) - CRUD 본문

JavaScript/NestJS

NestJS와 MongoDB 연결하기(3) - CRUD

크런키스틱 2021. 10. 8. 17:26
728x90

이번 포스트에서는 cats 스키마에 CRUD를 진행하고 확인해본다.

코드에 대한 내용이 이해가 가지 않는다면 NestJS의 기본 사용법 포스트를 보고 오기를 바란다.

 

1. Create

controller

// cats.controller.ts

import { Controller, Post, Body } from '@nestjs/common';
import { CatsService } from './cats.service';
import { CreateCatDto } from './dto/create-cat.dto';
import { Cat } from './schemas/cat.schema';

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

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

service

// 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';

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

    async create(catData: CreateCatDto) {
        let latestCat = await this.catModel.findOne().sort({id: -1});
        let thisId = latestCat ? latestCat.id+1 : 0;
        return await this.catModel.create({ ...catData, id: thisId});
    }
}

확인(Postman, Robo3t)

2. Read

controller

// cats.controller.ts

import { Controller, Get, Param } from '@nestjs/common';
import { CatsService } from './cats.service';
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) {
        return await this.catsService.getOne(catId);
    }
}

service

// cats.service.ts

import { Model } from 'mongoose';
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Cat, CatDocument } from './schemas/cat.schema';

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

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

    async getOne(catId: number): Promise<Cat> {
        const cat = await this.catModel.findOne({"id": catId});
        if(!cat) {
            throw new NotFoundException(`Cat with id: ${catId} not found.`);
        }
        return cat;
    }
}

확인

          getAll

          getOne(존재할 경우)

          getOne(존재하지 않을 경우)

 

3. Update

controller

// cats.controller.ts

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

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

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

service

// cats.service.ts

import { Model } from 'mongoose';
import { Injectable, NotFoundException } 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 getOne(catId: number): Promise<Cat> {
        const cat = await this.catModel.findOne({"id": catId});
        if(!cat) {
            throw new NotFoundException(`Cat with id: ${catId} not found.`);
        }
        return cat;
    }

    async update(catId: number, catData: UpdateCatDto) {
        const cat = await this.getOne(catId);
        if(cat) {
            return await this.catModel.updateOne({ "id": catId }, catData);
        }
    }
}

확인

4. Delete

controller

// cats.controller.ts

import { Controller, Delete, Param } from '@nestjs/common';
import { CatsService } from './cats.service';
import { Cat } from './schemas/cat.schema';

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

    @Delete(":id")
    async remove(@Param("id") catId: number) {
        return await this.catsService.remove(catId);
    }
}

service

// cats.service.ts

import { Model } from 'mongoose';
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Cat, CatDocument } from './schemas/cat.schema';

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

    async getOne(catId: number): Promise<Cat> {
        const cat = await this.catModel.findOne({"id": catId});
        if(!cat) {
            throw new NotFoundException(`Cat with id: ${catId} not found.`);
        }
        return cat;
    }

    async remove(catId: number) {
        const cat = await this.getOne(catId);
        if(cat) {
            return await this.catModel.remove({ "id": catId });
        }
    }
}

확인

 

 

5. 전체코드

controller

// cats.controller.ts

import { Controller, Get, Post, Patch, Delete, Param, Body } 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) {
        return await this.catsService.getOne(catId);
    }

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

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

    @Delete(":id")
    async remove(@Param("id") catId: number) {
        return await this.catsService.remove(catId);
    }
}

service

// cats.service.ts

import { Model } from 'mongoose';
import { Injectable, NotFoundException } 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(catId: number): Promise<Cat> {
        const cat = await this.catModel.findOne({"id": catId});
        if(!cat) {
            throw new NotFoundException(`Cat with id: ${catId} not found.`);
        }
        return cat;
    }

    async create(catData: CreateCatDto) {
        let latestCat = await this.catModel.findOne().sort({id: -1});
        let thisId = latestCat ? latestCat.id+1 : 0;
        
        return await this.catModel.create({ ...catData, id: thisId});
    }

    async update(catId: number, catData: UpdateCatDto) {
        const cat = await this.getOne(catId);
        if(cat) {
            return await this.catModel.updateOne({ "id": catId }, catData);
        }
    }

    async remove(catId: number) {
        const cat = await this.getOne(catId);
        if(cat) {
            return await this.catModel.remove({ "id": catId });
        }
    }
}

이상으로 cats 스키마를 CRUD하는 코드를 살펴보았다.

728x90