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

如何在HotChocolate MongoDB集成中实现软删除全局过滤排除已删记录

如何在HotChocolate MongoDB集成中实现软删除全局过滤?

当然可以实现,我们可以借助HotChocolate提供的MongoDB查询拦截机制,给所有实现ISoftDelete接口的实体自动注入IsDeleted = false的过滤条件,无需在每个查询中手动添加。

实现步骤:

1. 编写全局查询拦截器

实现IMongoDbQueryInterceptor接口,在查询执行前动态添加软删除过滤逻辑:

using HotChocolate.Data.MongoDb;
using MongoDB.Driver;

public class SoftDeleteQueryInterceptor : IMongoDbQueryInterceptor
{
    public void OnBeforeQueryExecution<T>(IMongoQueryable<T> queryable, MongoDbQueryContext context)
    {
        // 检查当前实体是否实现了ISoftDelete接口
        if (typeof(ISoftDelete).IsAssignableFrom(typeof(T)))
        {
            // 动态添加IsDeleted=false的过滤条件
            var filter = Builders<T>.Filter.Eq("IsDeleted", false);
            context.Queryable = queryable.Where(filter);
        }
    }
}

2. 注册拦截器到依赖注入容器

在GraphQL服务配置中注册这个拦截器,让HotChocolate处理MongoDB查询时自动应用过滤:

// Program.cs 或 Startup.cs
builder.Services
    .AddGraphQLServer()
    .AddMongoDbFiltering()
    .AddMongoDbSorting()
    .AddMongoDbProjections()
    .AddQueryType<Query>()
    // 注册软删除查询拦截器
    .AddMongoDbQueryInterceptor<SoftDeleteQueryInterceptor>();

3. 验证效果

完成配置后,所有针对实现ISoftDelete接口的实体的Find、Aggregation操作,都会自动带上IsDeleted = false的过滤条件:

  • 客户端的GraphQL请求永远无法获取到已标记删除的记录
  • 开发人员不需要在每个查询里手动添加过滤逻辑

特殊场景处理

如果需要在后台任务(比如定期清理已删除记录)中查询所有记录(包括已删除的),可以直接使用MongoDB原生驱动进行操作,绕过HotChocolate的查询拦截器即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 20:03:19