Mongoose ObjectId类型不兼容TypeScript报错求助
解决Mongoose中Types.ObjectId与Schema.Types.ObjectId类型不兼容问题
错误场景
你遇到的TypeScript错误如下:
类型“import("mongoose").Types.ObjectId”无法分配给类型“import("mongoose").Schema.Types.ObjectId”。类型“ObjectId”缺少类型“ObjectId”中的以下属性:auto、defaultOptions、OptionsConstructor、cast及另外20个属性。ts(2345)
问题出在将字符串转换为mongoose.Types.ObjectId实例后,传给Schema中定义为mongoose.Schema.Types.ObjectId的字段时类型不匹配,相关代码:
const questId = new mongoose.Types.ObjectId(questionId as string ) const response = await this.__questionRepository.createNewAnswer( answer, questId,// 此处触发上述TypeScript错误 userId, userType ); // Schema中questionId的定义: questionId: { type: mongoose.Schema.Types.ObjectId, ref: 'Question', required: true }
解决方案
方案1:统一Schema中的类型定义
把Schema里的questionId类型从mongoose.Schema.Types.ObjectId替换为mongoose.Types.ObjectId,和创建实例的类型保持一致:
questionId: { type: mongoose.Types.ObjectId, ref: 'Question', required: true }
方案2:类型断言匹配Schema类型
如果不想修改Schema定义,直接将创建的questId断言为mongoose.Schema.Types.ObjectId类型:
const questId = new mongoose.Types.ObjectId(questionId as string) as mongoose.Schema.Types.ObjectId;
方案3:检查Mongoose依赖一致性
如果上述方法无效,可能是项目中重复安装了Mongoose(比如子依赖和主依赖版本不一致),导致类型定义来自不同模块。执行以下命令重新安装依赖:
rm -rf node_modules package-lock.json npm install
内容的提问来源于stack exchange,提问作者Aswanth
相关产品推荐
相关产品推荐

