如何在nestjs/mongoose中的schema类中定义mongoose方法?

10

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

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包在类架构中编写方法?


那将是实例方法。您是否在寻找静态方法? - Chau Tran
不,我正在寻找实例方法。我无法在类内定义它。 - Sajjad Hadafi
模式(Schema)将肯定返回undefined,因为validatePassword是一个实例方法,它在模型上而不是模式上。 - Chau Tran
是的,你说得没错,但关键是如何在模式上编写方法。 - Sajjad Hadafi
3个回答

29

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

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

你好,我是nestjs中的typed mongo新手。为什么我们不能在@Schema装饰器中使用methods选项定义这些实例方法呢?我尝试过了,但好像不起作用!感谢您提供的解决方案,它很有效!只是想知道为什么要在装饰器中提供它,以及您是否知道如何使用它。@Suroor Ahmmad - utsavojha95
1
通过 @Schema() 装饰器,你只能指定模式而不能在其中定义方法。 - Suroor Ahmmad
好的,谢谢。我只是在想为什么我们可以在@nestjs/mongoose的@Schema()装饰器中定义一个带有函数的实例/方法对象。但是,是的,它不起作用,我想知道我们可以将这个选项传递给@Schema装饰器的用途是什么。 - utsavojha95

0
使用这个函数代替 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;
}

0
尝试使用AuthSchema.loadClass(Auth)高级模式:使用loadClass()从ES6类创建):
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;

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

// This function lets you pull in methods, statics, and virtuals from an ES6 class.
AuthSchema.loadClass(Auth);

确保您在方法中使用的所有属性都使用了@Prop()装饰器进行注释,否则它们将为undefined。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接