Issue
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?
Solution
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);
};
Answered By - Suroor Ahmmad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.