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

Prisma结合MongoDB查询含/不含deletedAt字段的未删除评论

解决方案

在MongoDB中,未添加deletedAt字段的旧评论,无法通过deletedAt: null或deletedAt: undefined匹配到,需要用字段存在性检查来兼容这类数据。你可以通过Prisma的exists操作符实现需求,修改后的查询代码如下:

const article = await prisma.article.findUnique({
    where: {
        id: articleId
    },
    include: {
        comments: {
            where: {
                parentId: null,
                OR: [
                    { deletedAt: null },
                    { deletedAt: { exists: false } }
                ]
            },
            orderBy: {
                createdAt: 'desc'
            },
        },
        upvotes: true,
    }
});

关键说明

  • { deletedAt: { exists: false } }:匹配MongoDB中不存在deletedAt字段的旧评论
  • { deletedAt: null }:匹配添加deletedAt字段后,未被删除(字段值为null)的新评论
  • 两者通过OR组合,即可覆盖所有未被删除的评论场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 15:12:10