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

Prisma findFirstOrThrow未抛异常反而返回首个记录求助

Prisma findFirstOrThrow 未按预期抛出异常,反而返回首条记录

我在使用Prisma编写测试时遇到问题:findFirstOrThrow方法未按预期在无匹配结果时抛出异常,反而返回数据库中的首个记录。使用的Prisma版本为^4.8.0。

测试代码如下:

console.log('sessionId', this.ctx.session?.user?.id);

const author = await this.db.author.findFirstOrThrow({
  where: { userId: this.ctx.session?.user?.id },
  select: { id: true },
});

console.log({ author });

测试日志输出:

RERUN  src/api/service.ts x31

stdout | src/api/service.test.ts > BlockService > block creation > without an author
sessionId undefined

stdout | src/api/service.test.ts > BlockService > block creation > without an author
{ author: { id: 'cle79pisg007hb2b8rhpii1ws' } }

可见,即使this.ctx.session?.user?.id为undefined,Prisma仍返回authors表中的首个记录。

我已尝试的操作:

  • 测试时不填充authors表,方法会抛出异常;
  • 填充单个作者记录时,返回该记录;
  • 显式传入undefined作为userId,仍返回首个记录。

内容的提问来源于stack exchange,提问作者Xiduzo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:31:15