어제 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 끝!