How to define mongoose method in schema class with using nestjs/mongoose?

Viewed 4881

I want to implement method in schema class like below.

import { SchemaFactory, Schema, Prop } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import bcrypt from 'bcrypt';

@Schema()
export class Auth extends Document {
  @Prop({ required: true, unique: true })
  username: string;

  @Prop({ required: true })
  password: string;

  @Prop({
    methods: Function,
  })
  async validatePassword(password: string): Promise<boolean> {
    return bcrypt.compareAsync(password, this.password);
  }
}
export const AuthSchema = SchemaFactory.createForClass(Auth);

this schema return undefined when log the method . How can I write method in class schema with nestjs/mongoose package?

2 Answers

You can use below approach to achieve this.

@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);
};

Use this function instead of SchemaFactory.createForClass(Auth):

export function createSchema(document: any) {
  const schema = SchemaFactory.createForClass(document);

  const instance = Object.create(document.prototype);

  for (const objName of Object.getOwnPropertyNames(document.prototype)) {
    if (
      objName != 'constructor' &&
      typeof document.prototype[objName] == 'function'
    ) {
      schema.methods[objName] = instance[objName];
    }
  }

  return schema;
}
Related