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

NestJS+TypeORM对接MongoDB时报Cannot read 'prototype' of undefined错误

问题原因

该报错是TypeORM版本与MongoDB官方Node驱动版本不兼容导致的:

你使用的TypeORM 0.2.x版本仅适配MongoDB 3.x版本的Node驱动,如果你安装了4.x及以上版本的MongoDB驱动,高版本驱动的FindCursor API发生了不兼容变更,TypeORM调用toArray方法时就会触发Cannot read property 'prototype' of undefined错误。

解决方案
  • 首先卸载当前安装的不兼容版本MongoDB驱动:
npm uninstall mongodb
# 或使用yarn
yarn remove mongodb
  • 安装对应TypeORM版本适配的MongoDB驱动:
    如果你使用TypeORM 0.2.x版本,执行:
    npm install mongodb@3.7.3
    # 或使用yarn
    yarn add mongodb@3.7.3
    
    如果你使用TypeORM 0.3.x及以上版本,执行:
    npm install mongodb@4.17.1
    # 或使用yarn
    yarn add mongodb@4.17.1
    
  • 额外校验项:确认你的Offices实体类正确使用@Entity()装饰器修饰,且在TypeORM配置的entities数组中已引入该实体,同时offices.service.ts中注入仓库的代码写法正确:
// offices.service.ts 注入示例
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MongoRepository } from 'typeorm';
import { Offices } from './entities/offices.entity';

@Injectable()
export class OfficesService {
  constructor(
    @InjectRepository(Offices)
    private officesRepository: MongoRepository<Offices>,
  ) {}

  // 你的findAll方法
}
  • 完成上述操作后重启项目,再调用接口即可正常返回数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:00:05