NodeJS+TypeORM控制器中patientRepository为undefined的问题求助
问题分析与解决方案
错误Cannot read property 'patientRepository' of undefined的核心原因是:getAll方法被作为路由处理函数传递时,JavaScript的函数调用丢失了原有的this绑定,导致方法内部的this指向undefined,无法访问实例属性patientRepository。
以下是三种可行的解决方式:
方法1:在构造函数中手动绑定this
通过bind方法将getAll的this强制绑定到控制器实例,确保无论如何调用方法,this都指向当前实例。
export class PatientController { patientRepository: Repository<Patient>; constructor() { this.patientRepository = AppDataSource.getRepository(Patient); // 绑定this到当前实例 this.getAll = this.getAll.bind(this); } async getAll(_req: Request, res: Response, next: NextFunction) { try { const patients = await this.patientRepository.find(); res.status(200).json(patients); } catch (err: any) { res.status(500).json({ message: err.message }); } finally { next(); } } }
方法2:使用箭头函数定义方法
箭头函数不会创建自身的this上下文,会继承外层作用域的this,天然保证方法内部的this指向控制器实例。
export class PatientController { patientRepository: Repository<Patient>; constructor() { this.patientRepository = AppDataSource.getRepository(Patient); } // 用箭头函数定义路由方法 getAll = async (_req: Request, res: Response, next: NextFunction) => { try { const patients = await this.patientRepository.find(); res.status(200).json(patients); } catch (err: any) { res.status(500).json({ message: err.message }); } finally { next(); } } }
方法3:框架层面的依赖注入(适用于NestJS场景)
如果使用NestJS框架,建议通过框架提供的依赖注入机制获取Repository,同时框架会自动处理this绑定问题,避免手动维护:
import { Controller, Get, Res, Next, HttpException, HttpStatus } from '@nestjs/common'; import { Response, NextFunction } from 'express'; import { Repository } from 'typeorm'; import { InjectRepository } from '@nestjs/typeorm'; import { Patient } from './patient.entity'; @Controller('patients') export class PatientController { constructor( // 通过依赖注入自动注入Repository实例 @InjectRepository(Patient) private readonly patientRepository: Repository<Patient>, ) {} @Get() async getAll(@Res() res: Response, @Next() next: NextFunction) { try { const patients = await this.patientRepository.find(); res.status(HttpStatus.OK).json(patients); } catch (err) { throw new HttpException(err.message, HttpStatus.INTERNAL_SERVER_ERROR); } finally { next(); } } }
内容的提问来源于stack exchange,提问作者Mikeul
相关产品推荐
相关产品推荐

