Hi i want access my mongoose static from my hook but i get error my code is:
import {Document,Model,Types,Schema,model} from "mongoose";
interface IReview extends Document{
rating:number;
title:string;
comment:string;
}
interface IReviewModel extends Model<IReview>{
calculateAvgRating(prodoctId:typeof Types.ObjectId):any;
}
const reviewSchema=new Schema<IReview,IReviewModel>({
rating:Number,
title:String,
comment:String
})
reviewSchema.statics.changeTitle=async function(title:string){
console.log(title)
}
reviewSchema.pre("save",async function(){
// here i get typescript error property changeTitle does not exist on type 'Function'
await this.constructor.changeTitle(this.title);
})
const ReviewModel=model<IReview,IReviewModel>("Review",reviewSchema)
export default ReviewModel;
what i can do for fixing this issue.
if you can point me too document or better answer me here thank you for your help.
Error you are seeing is because the this.constructor in the pre save hook of the Mongoose schema refers to the model's constructor, which TypeScript doesn't directly understand to have your custom static methods like changeTitle. To fix this, you can give TypeScript a hint about the type of this.constructor so it knows about your custom static methods.
import { Document, Model, Types, Schema, model } from "mongoose";
interface IReview extends Document {
rating: number;
title: string;
comment: string;
}
interface IReviewModel extends Model<IReview> {
changeTitle(title: string): void; // add this method signature
calculateAvgRating(prodoctId: typeof Types.ObjectId): any;
}
const reviewSchema = new Schema<IReview, IReviewModel>({
rating: Number,
title: String,
comment: String
});
reviewSchema.statics.changeTitle = function (title: string) {
console.log(title);
}
reviewSchema.pre("save", async function () {
const model = this.constructor as IReviewModel;
await model.changeTitle(this.title);
});
const ReviewModel = model<IReview, IReviewModel>("Review", reviewSchema);
export default ReviewModel;