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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:32:16