TypeScript中Mongoose Query类型不存在start属性的报错求助
解决Mongoose Query钩子中添加自定义属性的TypeScript类型报错
在TypeScript中给Mongoose Query对象添加自定义属性时,因为默认的Query类型没有该属性定义,所以会触发类型报错。解决方法是通过TypeScript的模块扩展机制,给Query类型添加自定义属性的类型声明:
步骤1:添加类型声明文件
在项目中创建一个类型声明文件(比如src/types/mongoose.d.ts),内容如下:
import 'mongoose'; declare module 'mongoose' { interface Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> { start?: number; } }
步骤2:配置TypeScript识别声明文件
确保你的tsconfig.json中include字段包含了这个声明文件的路径,示例配置:
{ "compilerOptions": { // 你的其他编译配置 }, "include": [ "src/**/*", "src/types/**/*.d.ts" ] }
步骤3:原代码正常使用
此时你的钩子函数中给this.start赋值和读取的操作就不会再触发类型报错了,同时建议补上Schema中用到的字段类型定义,避免后续其他类型问题:
import mongoose from 'mongoose'; interface TourSchemaTypes { name: string; secretTour?: boolean; } const tourSchema = new mongoose.Schema<TourSchemaTypes>({ name: { type: String, required: [true, 'A tour must have a name'], unique: true, }, secretTour: { type: Boolean, default: false } }); tourSchema.pre(/^find/, function (next) { this.find({ secretTour: { $ne: true } }); this.start = Date.now(); next(); }); tourSchema.post(/^find/, function (docs, next) { console.log(`Query took ${Date.now() - this.start} milliseconds`); console.log(docs); next(); }); const Tour = mongoose.model<TourSchemaTypes>('Tour', tourSchema);
内容的提问来源于stack exchange,提问作者champer
相关产品推荐
相关产品推荐

