Mongoose find方法能否实现IntelliSense?TypeScript使用疑问
解决Mongoose find方法filter参数无IntelliSense的问题
这不是Mongoose的已知限制,大概率是你的配置或模型定义方式需要调整,以下是具体解决步骤:
1. 确保使用Mongoose 6.0+版本
Mongoose从6.0版本开始大幅优化了TypeScript支持,包括filter参数的类型推断。如果你的版本低于6.0,先升级:
npm install mongoose@latest
2. 检查TypeScript配置
确保tsconfig.json中开启strict模式,这是TypeScript类型推断正常工作的基础:
{ "compilerOptions": { "strict": true, "esModuleInterop": true, "skipLibCheck": true, "target": "ES2020", "module": "CommonJS", "moduleResolution": "Node" } }
3. 优化模型定义
你当前的接口定义逻辑正确,但可以调整Schema泛型的使用方式,让Mongoose更准确地推断类型:
import mongoose from 'mongoose'; interface Icd_9Attrs { description: string; code: string; } interface Icd_9Doc extends mongoose.Document { description: string; code: string; } interface Icd_9Model extends mongoose.Model<Icd_9Doc> { build(attrs: Icd_9Attrs): Icd_9Doc; } // 移除Schema泛型中的第二个模型类型参数,让Mongoose自动关联 const icd_9Schema = new mongoose.Schema<Icd_9Doc>({ description: { type: String, required: true, }, code: { type: String, required: true, }, }); icd_9Schema.statics.build = (attrs: Icd_9Attrs) => { return new Icd_9(attrs); }; const Icd_9 = mongoose.model<Icd_9Doc, Icd_9Model>('Icd_9', icd_9Schema, 'icd_9'); export { Icd_9 };
4. 手动约束filter类型(临时方案)
如果上述调整后仍有问题,可以手动导入FilterQuery类型强制约束参数:
import { FilterQuery } from 'mongoose'; // 使用find时显式指定类型 Icd_9.find({ description: 'test' } as FilterQuery<Icd_9Doc>);
完成以上步骤后,find方法的filter参数应该就能正常显示字段的类型提示,不再标记为any。
内容的提问来源于stack exchange,提问作者limdev
相关产品推荐
相关产品推荐

