最近正在学习nestjs,自己安装官网文档搭建了一个demo项目,使用TypeORM 连接mysql和MondoDb。mysql连接后使用正常,MongoDB 连接却出现了问题。
附上源代码:
// 连接配置
TypeOrmModule.forRootAsync({
name: 'mongodb',
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => {
return {
type: 'mongodb',
url: configService.get('mongo.URL'),
database: configService.get('mongo.DATABASE'),
entities: ['dist/**/mongo/*.entity{.ts,.js}'],
}
},
}),
// service 中读取mongo数据
async findOne(): Promise {
try {
const recordRepository = getMongoRepository(Record, 'mongodb');
const record = await recordRepository.findOne({ firstName: 'xiaoditian' });
this.logger.info(JSON.stringify(record))
return record;
} catch(err) {
console.log(err)
}
}
结果报错:
TypeError: Cannot read property 'toArray' of undefined
at FindCursor.cursor.toArray (D:\selfpractise\test\lgwWx\src\entity-manager\MongoEntityManager.ts:709:38)
at MongoEntityManager. (D:\selfpractise\test\lgwWx\src\entity-manager\MongoEntityManager.ts:190:55)
at step (D:\selfpractise\test\lgwWx\node_modules\typeorm\node_modules\tslib\tslib.js:143:27)
at Object.next (D:\selfpractise\test\lgwWx\node_modules\typeorm\node_modules\tslib\tslib.js:124:57)
at fulfilled (D:\selfpractise\test\lgwWx\node_modules\typeorm\node_modules\tslib\tslib.js:114:62)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
直接当场懵逼。。。
根据提示,找到TypeORM 源码下的\src\entity-manager\MongoEntityManager.ts
发现第690行
ParentCursor.prototype.toArray.call()
ParentCursor 为 undefined
ParentCursor 定义在 686 行
const ParentCursor = PlatformTools.load("mongodb").Cursor;
进一步查找PlatformTools.load方法定义:
static load(name: string): any {
// if name is not absolute or relative, then try to load package from the node_modules of the directory we are currently in
// this is useful when we are using typeorm package globally installed and it accesses drivers
// that are not installed globally
try {
// switch case to explicit require statements for webpack compatibility.
switch (name) {
/**
* mongodb
*/
case "mongodb":
return require("mongodb");
...
}
} catch (err) {
return require(path.resolve(process.cwd() + "/node_modules/" + name));
}
}
这里引入了mongodb 包,在项目中打印一下 mongodb 包
没有发现Cursor对象,这时候突然想是不是TypeORM依赖的mongodb包版本不对
,打开TypeORM的package.json文件,发现版本为 3.6.2,自己项目中的版本为4.0.0。。。直接原地爆炸,自己的粗心导致浪费了半天时间,大家引以为戒。