You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Nestjs Mongoose项目中TypeScript报CannotDetermineTypeError问题

问题原因

TypeScript 的联合类型仅存在于编译阶段,编译为 JavaScript 后类型信息会被抹除,@nestjs/mongoose 无法在运行时自动识别 extra_id 字段允许的存储类型,因此抛出该错误。

解决方法

给 extra_id 字段对应的 @Prop 装饰器添加 type 配置,显式指定允许的类型即可,两种可选方案如下:

  • 方案一:明确仅允许存储字符串和数字,直接传入类型数组
    修改后的完整代码如下:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema({ timestamps: true })
export class Tests {
  @Prop({ required: true, index: true })
  testid: number;

  // 新增type配置,显式指定允许的类型为字符串或数字
  @Prop({ required: false, type: [String, Number] })
  extra_id: string | number;

  @Prop({ required: false })
  points: number;
}

export type TestsDocument = Tests & Document;
export const TestsSchema = SchemaFactory.createForClass(Tests);
  • 方案二:如果字段允许存储任意类型,可指定为 Mongoose 的 Mixed 类型
    需要先引入 Schema 从 mongoose,然后修改对应装饰器:
// 顶部引入
import { Schema } from 'mongoose';

// extra_id字段装饰器修改为
@Prop({ required: false, type: Schema.Types.Mixed })
extra_id: string | number;

内容的提问来源于stack exchange,提问作者saravanan mp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 06:27:03