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

Prisma中使用not过滤自定义Type字段失效问题咨询

问题描述

我定义了如下自定义Type:

type Details {
  birthday String?
  phone    String?
  email    String?
}

对应的Prisma Model:

model profiles {
  id           String            @id @default(auto()) @map("_id") @db.ObjectId
  schools      School[]
  details      Details?
  skills       Skill[]
  allSkills    String?
}

尝试使用not操作符查询过滤:

const profiles = await prisma.profiles.findMany({
  where: {
    details: {
      email: {
        not: null,
      },
    },
  },
});

但操作无效,TypeScript不会为email字段(类型为string | undefined | null)提示not操作符。但将Details改为Prisma Model后:

model Details {
  birthday String?
  phone    String?
  email    String?
}

TypeScript就会正常提示not操作符。想问为什么自定义Type和Model的过滤方式不能保持一致?我认为not过滤应该对Type和Model都生效。

原因分析与解答

这是因为Prisma对自定义复合Type和Model的查询支持逻辑存在本质差异:

  • Model是数据库层面的独立实体,对应数据库中的表/集合,Prisma为其生成的查询API支持全套过滤操作(包括not、and、or等),这是因为数据库本身可以对表字段执行这类复杂条件过滤。
  • 自定义复合Type是嵌入式结构,它属于父Model的嵌套字段,并非独立的数据库实体。Prisma对嵌入式Type的查询支持有限,仅支持基础的相等匹配、存在性检查(如is、isNot),不支持not这类复杂逻辑操作——原因是嵌入式数据存储在父Model的同一条记录中,数据库层面无法对嵌套字段直接执行not这类逻辑过滤,Prisma也就没有为其生成对应的类型提示。

如果要实现排除details.email为null的效果,可以用isNot替代:

const profiles = await prisma.profiles.findMany({
  where: {
    details: {
      email: {
        isNot: null,
      },
    },
  },
});

该写法符合Prisma对嵌入式Type的查询规则,也能达到预期的过滤目的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 19:04:57