【问题标题】:How to define mongoose method in schema class with using nestjs/mongoose?如何使用 nestjs/mongoose 在模式类中定义 mongoose 方法?
【发布时间】:2025-12-21 03:35:11
【问题描述】:

我想在下面的模式类中实现方法。

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

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

【问题讨论】:

  • 那将是实例方法。您在寻找静态方法吗?
  • 不,我正在寻找实例方法。我无法在类中定义它
  • Schema 肯定会为validatePassword 返回undefined,因为它是模型上的实例方法,而不是模式。
  • 是的,你说的是真的,但关键是如何在模式上编写方法

标签: node.js mongodb typescript mongoose nestjs


【解决方案1】:

您可以使用以下方法来实现此目的。

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

【讨论】: