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

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ã

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:21:02