Hello everyone! I am a beginner in TS and NestJS, and I'm having trouble accessing req and res inside a pre-save hook. Can someone please take a look at my file and the image of the compiler error that I'm encountering? Could you explain why this error is happening?
Also, in the NestJs documentation under Techniques > mongo > hook, they suggest using hooks inside Mongoose.forFeatureAsync(), but I keep getting an error saying that my user model wasn't registered. Can anyone recommend the best practice for achieving this? I'm really struggling to figure out the best approach. Thank you for your time.
Here is the image of the error.
user.model.ts -
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import * as mongoose from 'mongoose';
import { Req , Res } from '@nestjs/common';
export type UserDocument = User & Document;
@Schema()
export class User {
constructor() {}
@Prop({
required: [true, 'Please enter first name'],
trim: true,
})
firstName: string;
@Prop({
required: [true, 'Please enter last name'],
trim: true,
})
lastName: string;
@Prop({
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
})
referer: mongoose.Types.ObjectId;
@Prop({
type: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
],
})
referees: mongoose.Types.ObjectId[];
@Prop()
referralCode: string;
@Prop({
default: 0,
})
transactions: number;
@Prop({
type: mongoose.Schema.Types.ObjectId,
ref: 'Account',
})
account: mongoose.Types.ObjectId;
}
export const UserSchema = SchemaFactory.createForClass(User);
UserSchema.pre('save', function ( req , res , next) {
let referralCode;
const random = Math.floor(Math.random() * 1000);
const number = random.toLocaleString('en-US', {
minimumIntegerDigits: 3,
useGrouping: false,
});
const finalNumber = number.toString();
const name = this.get('firstName');
if (name.length < 5) {
const repeat = 5 - name.length;
const str = 'X';
const repeatedString = str.repeat(repeat);
referralCode = name.concat(repeatedString).concat(finalNumber);
} else {
referralCode = name.substr(0, 5).concat(finalNumber);
}
this.set('referralCode', referralCode);
console.log(this);
next();
});