0sinf / express-board-app

express 프레임워크로 게시판 앱 만들기
0 stars 0 forks source link

mongoose typescript 적용하기 #8

Open 0sinf opened 2 years ago

0sinf commented 2 years ago

mongoose에 typescript 적용하기

interface 정의하기

스키마에 정의할 내용들 먼저 Interface로 정의한다. _id와 같은 도큐먼트에 포함된 것을 사용하려면 mongoose에 정의된 Document를 사용한다. (상속)

statics

모델의 static 함수를 정의하기 위해 interface를 정의할 땐, Model<T>를 사용한다.

interface IUserModel extends Model<IUser> {
  createUser: (email: string, password: string, name: string) => Promise<string>;
}

위와 같이 Model<T>를 상속받는 모델 interface를 정의한다.

instance method

생성된 instance의 메서드를 사용하기 위해서는 Document를 상속받는 것이 필요하다.

interface IUserDocument extends IUser, Document {
  verifyPassword: (password: string) => boolean;
}

스키마 선언과 모델 선언

new Schema<T>와 같은 형태로 도큐먼트를 전달한다.

model<IUserDocument, IUserModel>와 같은 형태로 모델을 생성할 땐, 도큐먼트와 모델을 전달한다. 모델이 없는 경우 도큐먼트만 전달한다.

0sinf commented 2 years ago

mongoose에서 timestamps: true 옵션을 사용할 때

먼저 interface에서 createdAt, updatedAt을 선언하고 타입은 Date로 사용한다.

0sinf commented 2 years ago

_id 대신 id로 도큐먼트 id를 호출할 수 있다.

_id는 객체 타입으로 (objectId) id는 string 타입으로 반환된다.

0sinf commented 2 years ago

select()

도큐먼트를 호출할 때 특정 필드값을 호출하거나 제외하고 호출할 수 있다.

await Model.findById(id).select(['contents'])

위와 같은 경우 objectId와 contents만 가져온다.

await Model.findById(id).select(['-contents'])

위와 같은 경우 contents 필드만 제외하고 모두 가져온다.

populate에서 select

populate에서 select을 사용하면, 두번째 인자로 select을 전달한다. (string의 형태로)

pagination

sort, skip, limit