diff --git a/mongo/mongo.go b/mongo/mongo.go index 59f51f9..edc8781 100644 --- a/mongo/mongo.go +++ b/mongo/mongo.go @@ -435,7 +435,7 @@ func (m *MongoDB) Delete(ctx context.Context, filter bson.M, collection string, count = r.DeletedCount err = m.CleanRedis(ctx, filter, user.TenantId, collection) //写日志 - m.log(ctx, filter, collection, nil, user.UserName, user.TenantId, "delete") + //m.log(ctx, filter, collection, nil, user.UserName, user.TenantId, "delete") return } @@ -465,7 +465,7 @@ func (m *MongoDB) Update(ctx context.Context, filter bson.M, update bson.M, coll } err = m.CleanRedis(ctx, filter, user.TenantId, collection) //写日志 - m.log(ctx, filter, collection, update, user.UserName, user.TenantId, "update") + //m.log(ctx, filter, collection, update, user.UserName, user.TenantId, "update") return } @@ -622,7 +622,7 @@ func (m *MongoDB) Insert(ctx context.Context, documents []interface{}, collectio ids = r.InsertedIDs err = m.CleanRedis(ctx, bson.M{}, user.TenantId, collection) //写日志 - m.log(ctx, nil, collection, ids, user.UserName, user.TenantId, "insert") + //m.log(ctx, nil, collection, ids, user.UserName, user.TenantId, "insert") return } @@ -658,9 +658,15 @@ func (m *MongoDB) Count(ctx context.Context, filter bson.M, collection string) ( return } -// EntityToBSONM 将 *entity/entity 转换为 bson.M +// EntityToBson 将 *entity/entity 转换为 bson.M // 支持传入值类型或指针类型,返回 bson.M 和错误信息 -func EntityToBSONM(entity interface{}) (bson.M, error) { +func EntityToBson(entity interface{}) (bson.M, error) { + return EntityToBsonWithFilter(entity, false) +} + +// EntityToBsonWithFilter 将 *entity/entity 转换为 bson.M,并可选择是否过滤空值 +// filterEmpty: 为 true 时会过滤掉空值字段(nil、空字符串、空切片、空map等) +func EntityToBsonWithFilter(entity interface{}, filterEmpty bool) (bson.M, error) { // 第一步:判断入参是否为 nil 或无效类型 if entity == nil { return nil, fmt.Errorf("传入的 entity 实例为 nil") @@ -677,5 +683,13 @@ func EntityToBSONM(entity interface{}) (bson.M, error) { if err != nil { return nil, fmt.Errorf("BSON 字节流反序列化为 bson.M 失败:%w", err) } + // 如果需要过滤空值 + if filterEmpty { + for key, value := range bsonMap { + if g.IsEmpty(value) { + delete(bsonMap, key) + } + } + } return bsonMap, nil }