lflov

Nest Repository 패턴 적용중 발생한 에러 본문

Blocker

Nest Repository 패턴 적용중 발생한 에러

마젠토브힘내부왕 2022. 12. 21. 18:30

현재 nest강의를 들으면서 Repository 패턴에 대해 배웠따.

 

express 에서의 Dao 단 처럼 DB와 관련된 것만 놓는 모듈을 의미한다고 이해했다.

 

그래서 관련 코드를 작성하고 있는데..

import { Injectable, HttpException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Cat } from './cats.schema';

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

  async existsByEmail(email: string): Promise<boolean> {
    try {
      const result = await this.catModel.exists({ email });
      return result;
    } catch (error) {
      throw new HttpException('db error', 400);
    }
  }
}

return result에서 에러가 발생한다...

 

 

이렇게 말이다... 어떻게 해결해야 할까

 

해결법

 

mongoose 공식문서에 확인해보니 mongoose v6부터 Model.exists의 타입이 boolean > { _id : ObjectId(...) } 이렇게 바뀐거같다

 

우리는 boolean의 Promise로 리턴받길 원하므로 

 

import { Injectable, HttpException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Cat } from './cats.schema';

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

  async existsByEmail(email: string): Promise<boolean> {
    try {
      const result = await this.catModel.exists({ email });
      if (result) return true;
      else return false;
    } catch (error) {
      throw new HttpException('db error', 400);
    }
  }
}

이런식으로 if문으로 해결할수 있다