[Nest.js] MongoDB CRUD

Woong·2022년 12월 15일
0

Nestjs

목록 보기
11/28

Model

  • Model 은 Schema 를 통해 정의된 생성자
    • Model 의 인스턴스가 document

Mongo 커넥션 설정

  • mongoose.set('debug', true) 를 통해 쿼리문을 출력하는 것이 가능
    • production 환경에서는 출력하지 않도록 적절히 config 적용
@Module({
  imports: [
    MongooseModule.forRoot(
      'mongodb://<username>:<password>@localhost:27017',
      {dbName: 'studentdb'}
    ),
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    mongoose.set('debug', process.env.NODE_ENV === 'development' ? true : false) // MongoDB 쿼리를 출력하는 옵션.
  }
}

Schema 정의

  • @Prop 이 있어야만 스키마에 반영된다.
  • virtual 메소드를 통해 저장되지 않는 속성 정의 가능
    • ex) 프론트엔드, 클라이언트 등에 리턴할 스키마 정의하는 데 활용
      • ex) password 제거 등
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"
@Schema()
export class Student {
   @Prop()
   name: string;
   @Prop()
   roleNumber: number;
   @Prop()
   class: number;
   @Prop()
   gender: string;
   @Prop()
   marks: number;
}
export const StudentSchema = SchemaFactory.createForClass(Student);
  • model 등록
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { StudentSchema } from './schema/student.schema';
@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost:27017/studentdb'),
    MongooseModule.forFeature([
      { name: 'Student', schema: StudentSchema } // 지정
    ])
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
  • CRUD 실행
    • upsert할 때에는 new:true가 포함되어야 새로 생성되는 document 를 리턴한다
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { CreateStudentDto } from 'src/dto/create-student.dto';
import { IStudent } from 'src/interface/student.interface';
import { Model } from "mongoose";
import { UpdateStudentDto } from 'src/dto/update-student.dto';
@Injectable()
export class StudentService {
constructor(@InjectModel('Student') private studentModel:Model<IStudent>) { }
async createStudent(createStudentDto: CreateStudentDto): Promise<IStudent> {
   const newStudent = await new this.studentModel(createStudentDto);
   return newStudent.save();
}
async updateStudent(studentId: string, updateStudentDto: UpdateStudentDto): Promise<IStudent> {
    const existingStudent = await this.studentModel.findByIdAndUpdate(studentId, updateStudentDto, { new: true });
   if (!existingStudent) {
     throw new NotFoundException(`Student #${studentId} not found`);
   }
   return existingStudent;
}
async getAllStudents(): Promise<IStudent[]> {
    const studentData = await this.studentModel.find();
    if (!studentData || studentData.length == 0) {
        throw new NotFoundException('Students data not found!');
    }
    return studentData;
}
async getStudent(studentId: string): Promise<IStudent> {
   const existingStudent = await this.studentModel.findById(studentId).exec();
   if (!existingStudent) {
    throw new NotFoundException(`Student #${studentId} not found`);
   }
   return existingStudent;
}
async deleteStudent(studentId: string): Promise<IStudent> {
    const deletedStudent = await this.studentModel.findByIdAndDelete(studentId);
   if (!deletedStudent) {
     throw new NotFoundException(`Student #${studentId} not found`);
   }
   return deletedStudent;
}
}

reference

0개의 댓글