NestJS中Prisma操作questionRecord报undefined错误的排查与解决
问题解决:NestJS调用创建接口触发TypeError: Cannot read properties of undefined (reading 'questionRecord')
问题场景
在NestJS项目中,基于Prisma定义的QuestionRecord模型创建问题记录时,调用创建接口抛出错误:
TypeError: Cannot read properties of undefined (reading 'questionRecord')
根因分析
该错误的核心原因是**PrismaQuestionRepository类未添加@Injectable()装饰器**。在NestJS的依赖注入体系中,只有被@Injectable()标记的类才能被DI容器管理,确保在需要注入的地方能获取到有效实例。如果缺少这个装饰器,当CreateQuestion这类服务尝试注入PrismaQuestionRepository时,无法拿到可用实例,后续调用其关联questionRecord的方法时就会触发undefined访问错误。
解决方案
在PrismaQuestionRepository类上添加NestJS的@Injectable()装饰器:
import { Injectable } from '@nestjs/common'; import { PrismaService } from './prisma.service'; // 其他必要导入 @Injectable() // 关键:添加该装饰器 export class PrismaQuestionRepository { constructor(private readonly prisma: PrismaService) {} // 示例创建方法 async createQuestionRecord(data: any) { return this.prisma.questionRecord.create({ data }); } }
添加装饰器后,NestJS的DI容器会正确识别并管理该仓库类的实例,服务注入时就能获取到可用对象,避免undefined相关错误。
内容的提问来源于stack exchange,提问作者Cauã
相关产品推荐
相关产品推荐

