如何在Prisma+MongoDB中筛选deletedAt不存在或为null的结果?
解决方案:筛选Prisma+MongoDB中deletedAt为null或不存在的记录
问题背景
使用Prisma搭配MongoDB实现软删除逻辑,CommentProject模型中deletedAt为可选DateTime字段,字段存在则表示记录已删除。需要筛选出deletedAt为null或完全不存在的记录,但直接使用deletedAt: null无法匹配字段不存在的记录,且Prisma暂不直接支持MongoDB的$exists运算符。
模型定义
model CommentProject { id String @id @default(auto()) @map("_id") @db.ObjectId content String deletedAt DateTime? modified Boolean @default(false) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt project Project @relation(fields: [projectId], references: [id]) projectId String @db.ObjectId author User @relation(fields: [authorId], references: [id], onDelete: Cascade) authorId String @db.ObjectId }
无效的尝试
const comments = await prisma.commentProject.findMany({ where: { projectId: input.projectId, deletedAt: null, // 无法返回deletedAt未定义的记录 }, });
可行方案
在不使用默认值、额外字段或原生查询的前提下,可通过Prisma的OR条件组合两种判断逻辑:
const comments = await prisma.commentProject.findMany({ where: { projectId: input.projectId, OR: [ { deletedAt: null }, { deletedAt: { not: { exists: true } } } ] }, });
通过not嵌套exists条件匹配字段不存在的记录,再结合deletedAt: null的条件,用OR合并后即可覆盖两种目标场景。
内容的提问来源于stack exchange,提问作者rooklee
相关产品推荐
相关产品推荐

