如何使用 nestjs/mongoose 在模式类中定义 mongoose 方法? [英] How to define mongoose method in schema class with using nestjs/mongoose?
本文介绍了如何使用 nestjs/mongoose 在模式类中定义 mongoose 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在架构类中实现方法,如下所示.
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);
这个模式在记录方法时返回 undefined .如何使用 nestjs/mongoose 包在类架构中编写方法?
this schema return undefined when log the method . How can I write method in class schema with nestjs/mongoose package?
推荐答案
您可以使用以下方法来实现.
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);
};
这篇关于如何使用 nestjs/mongoose 在模式类中定义 mongoose 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文