Skip to content

[공유] nestJS mongoose 스키마 가상필드 및 메소드 사용 방법 #13

@sween2591

Description

@sween2591

👩‍💻 공유 사항

가상필드 혹은 getter, setter 선언 방법입니다.

@ModelOptions({autoIndex: true, toJSON: {virtuals: true}}) //모든 필드에 인덱싱, 반환할때 get있는 가상필드 포함
export class Customer extends Document {
  @Prop()
  public firstName: string;

  @Prop()
  public lastName: string;

  @Prop({unique: true})
  public email: string;

  @Prop()
  public phone: string;
  
  @Prop()
  public address: string;
  
  @Prop()
  public description: string;

  // this will create a virtual property called 'fullName'
  public get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  public set fullName(full:string) {
    const [firstName, lastName] = full.split(' ');
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

메소드 선언 방법입니다.

@Schema()
export class Auth extends Document {
    ...
    
    validatePassword: Function;
}

export const AuthSchema = SchemaFactory.createForClass(Auth);

AuthSchema.methods.validatePassword = async function (password: string): Promise<boolean> {
    return bcrypt.compareAsync(password, this.password);
};

✅ 참고 사항

공유할 내용, 스크린샷 등을 넣어 주세요.

  • 추가적인 공유가 필요한 사항은 Comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions