NestJS+TypeORM对接MongoDB时报Cannot read 'prototype' of undefined错误
问题原因
该报错是TypeORM版本与MongoDB官方Node驱动版本不兼容导致的:
你使用的TypeORM 0.2.x版本仅适配MongoDB 3.x版本的Node驱动,如果你安装了4.x及以上版本的MongoDB驱动,高版本驱动的
FindCursorAPI发生了不兼容变更,TypeORM调用toArray方法时就会触发Cannot read property 'prototype' of undefined错误。
解决方案
- 首先卸载当前安装的不兼容版本MongoDB驱动:
npm uninstall mongodb # 或使用yarn yarn remove mongodb
- 安装对应TypeORM版本适配的MongoDB驱动:
如果你使用TypeORM 0.2.x版本,执行:
如果你使用TypeORM 0.3.x及以上版本,执行:npm install mongodb@3.7.3 # 或使用yarn yarn add mongodb@3.7.3npm 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
相关产品推荐
相关产品推荐

