MongoDB + NestJS 연동(2)

Jina Kim·2025년 7월 11일
post-thumbnail

어제 mongoDB에 데이터 저장까지 완료했음.
오늘은 NestJS에서 조회, 수정, 삭제까지 해보자.

데이터 저장

// cat.service.ts
@Injectable()
export class CatService {
  constructor(
    @InjectModel(Cat.name)
    private catModel: Model<CatDocument>,
  ) {}

  async createCat(catData: Partial<Cat>) {
    const cat = new this.catModel(catData);
    return cat.save();
  }
}

데이터 조회

 async getCat(
    cat_idx: number,
    pageDto: PageDto,
  ) {
    const cats = await this.catModel
      .find({ cat_idx })
      .sort({ createdAt: -1 }) // 최신순 정렬
      .skip((pageDto.page_no - 1) * pageDto.limit)
      .limit(pageDto.limit)
      .exec();

    const totalCount = await this.catModel.countDocuments({
      cat_idx,
    });

    return { data: cats, totalCount };
}

데이터 삭제

async deleteCat(id: string) {
    const result = await this.catModel.deleteOne({
      _id: id,
    });

    if (result.deletedCount === 0) {
      throw new Exception('UnableDeleteCat');
    }

    return result.deletedCount;
  }

데이터 수정

async updateCat(id: string, name: string) {
    const result = await this.catModel.findOneAndUpdate(
      { _id: id }, // 조건
      { name, updatedAt: new Date() }, // 수정할 값
      { new: true }, // 수정된 결과 리턴
    );

    if (!result) {
      throw new Exception('UnableUpdateCat');
    }

    return result;
  }

MongoDB + NestJS CRUD 끝!

profile
Hello, World!

0개의 댓글