如何使用 nestjs/mongoose 在模式类中定义 mongoose 方法?

Saj*_*afi 5 mongoose mongodb node.js typescript nestjs

我想在模式类中实现方法,如下所示。

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);
Run Code Online (Sandbox Code Playgroud)

记录方法时,此架构返回未定义。如何使用 nestjs/mongoose 包在类模式中编写方法?

Sur*_*mad 11

您可以使用以下方法来实现这一点。

@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);
};
Run Code Online (Sandbox Code Playgroud)