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

NestJS+TypeORM+MongoDB调用find方法报错Cannot read property 'prototype' of undefined

问题解决方案

错误根源

本次报错核心由两个问题共同导致:

  1. TypeORM版本与MongoDB Node.js驱动版本不兼容
  2. ObjectId类型使用错误,查询参数类型不匹配

具体修复步骤

  • 第一步:修复版本依赖不兼容问题
    TypeORM 0.2.x稳定版仅支持MongoDB 3.x版本的Node.js驱动,若你安装了4.x及以上版本的mongodb包就会触发Cannot read property 'prototype' of undefined报错,执行以下命令安装匹配版本:

    npm uninstall mongodb
    npm install mongodb@3.7.3
    

    若你使用的是TypeORM 0.3.x版本,建议降级到0.2.45稳定版规避MongoDB适配问题:

    npm uninstall typeorm @nestjs/typeorm
    npm install typeorm@0.2.45 @nestjs/typeorm@8.0.3
    
  • 第二步:修正实体类ObjectId类型配置
    修改model/user.entity.ts文件,将_id字段的类型从string改为MongoDB原生的ObjectId类型:

    import { Entity, Column, ObjectIdColumn, OneToMany } from 'typeorm';
    import { ObjectId } from 'mongodb'; // 新增导入
    import { Context } from './context.entity'; // 确保Context实体路径正确
    
    @Entity({ name: 'User' })
    export class User {
      @ObjectIdColumn()
      _id: ObjectId; // 类型从string改为ObjectId
    
      @Column({ type: 'varchar', length: 50 })
      username: string;
    
      // 确认Context实体已正确配置@ManyToOne关联,否则先注释该行测试
      @OneToMany((type) => Context, (context) => context.user)
      contexts: Context[];
    }
    
  • 第三步:修正单条查询的参数类型
    前端传入的id是字符串格式,需要转为ObjectId类型后再进行查询,修改user.service.ts的get方法:

    import { ObjectId } from 'mongodb'; // 新增导入
    
    // 其他代码不变
    public async get(id: string) {
      const user = await this.userRepository.findOne({ _id: new ObjectId(id) });
      if (!user) {
        const errors = { User: ' not found' };
        throw new HttpException({ errors }, 401);
      }
      return this.buildUserRO(user);
    }
    

    同时修改user.interface.ts中UserData的_id类型保持一致性:

    import { ObjectId } from 'mongodb';
    
    export interface UserData {
      username: string;
      _id: ObjectId | string; // 也可在buildUserRO方法中调用_id.toString()转为字符串返回
    }
    

验证

完成以上修改后重启Nest服务,先调用创建用户接口写入数据,再调用查询接口即可正常获取数据,不会再抛出报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:15:02