2026-01-09 19:45:50 +08:00
|
|
|
|
// =============================================================================
|
2026-01-09 21:08:31 +08:00
|
|
|
|
// MongoDB 业务操作封装
|
|
|
|
|
|
// 提供向后兼容的CRUD操作方法,支持多数据源
|
2026-01-09 19:45:50 +08:00
|
|
|
|
// =============================================================================
|
|
|
|
|
|
|
2025-11-25 11:51:16 +08:00
|
|
|
|
package mongo
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"context"
|
2025-12-04 17:38:34 +08:00
|
|
|
|
"errors"
|
|
|
|
|
|
"fmt"
|
2025-11-25 13:47:20 +08:00
|
|
|
|
"time"
|
|
|
|
|
|
|
2026-01-26 09:02:49 +08:00
|
|
|
|
"gitee.com/red-future---jilin-g/common/log/consts"
|
|
|
|
|
|
|
2026-01-06 17:01:10 +08:00
|
|
|
|
"gitee.com/red-future---jilin-g/common/beans"
|
2026-01-07 18:27:43 +08:00
|
|
|
|
"gitee.com/red-future---jilin-g/common/log/model/entity"
|
2025-12-04 17:38:34 +08:00
|
|
|
|
"gitee.com/red-future---jilin-g/common/redis"
|
2025-11-25 11:51:16 +08:00
|
|
|
|
"gitee.com/red-future---jilin-g/common/utils"
|
2026-01-09 19:45:50 +08:00
|
|
|
|
"github.com/gogf/gf/v2/container/gvar"
|
2025-11-25 11:51:16 +08:00
|
|
|
|
"github.com/gogf/gf/v2/errors/gerror"
|
|
|
|
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
|
|
|
|
"github.com/gogf/gf/v2/os/glog"
|
2026-01-09 19:45:50 +08:00
|
|
|
|
"github.com/gogf/gf/v2/os/grpool"
|
2025-12-02 11:27:35 +08:00
|
|
|
|
"github.com/gogf/gf/v2/os/gtime"
|
|
|
|
|
|
"github.com/gogf/gf/v2/util/gconv"
|
2025-11-25 13:47:20 +08:00
|
|
|
|
"go.mongodb.org/mongo-driver/v2/bson"
|
|
|
|
|
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
|
|
|
|
|
"go.mongodb.org/mongo-driver/v2/mongo/options"
|
2025-11-25 11:51:16 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2026-01-09 19:45:50 +08:00
|
|
|
|
// =============================================================================
|
|
|
|
|
|
// 向后兼容的MongoDB结构体
|
|
|
|
|
|
// =============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
type MongoDB struct {
|
2026-01-21 16:33:37 +08:00
|
|
|
|
noCache bool
|
2026-01-09 19:45:50 +08:00
|
|
|
|
dataSource string // 数据源名称,默认为 "default"
|
2026-01-21 16:33:37 +08:00
|
|
|
|
noTenantId bool // 是否跳过租户过滤
|
2026-01-09 19:45:50 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func DB(cache ...bool) *MongoDB {
|
|
|
|
|
|
return &MongoDB{
|
2026-01-21 16:33:37 +08:00
|
|
|
|
noCache: false,
|
2026-01-09 19:45:50 +08:00
|
|
|
|
dataSource: "default",
|
2026-01-21 16:33:37 +08:00
|
|
|
|
noTenantId: false,
|
2026-01-09 19:45:50 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-12-19 15:17:19 +08:00
|
|
|
|
|
2026-01-09 19:45:50 +08:00
|
|
|
|
// WithDataSource 指定使用的数据源
|
|
|
|
|
|
func (m *MongoDB) WithDataSource(name string) *MongoDB {
|
|
|
|
|
|
m.dataSource = name
|
|
|
|
|
|
return m
|
2025-12-19 15:17:19 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-21 16:33:37 +08:00
|
|
|
|
// NoCache 不使用缓存
|
|
|
|
|
|
func (m *MongoDB) NoCache() *MongoDB {
|
|
|
|
|
|
m.noCache = true
|
|
|
|
|
|
return m
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// NoTenantId 不使用租户过滤
|
|
|
|
|
|
func (m *MongoDB) NoTenantId() *MongoDB {
|
|
|
|
|
|
m.noTenantId = true
|
|
|
|
|
|
return m
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-09 19:45:50 +08:00
|
|
|
|
// =============================================================================
|
|
|
|
|
|
// 向后兼容的全局变量和方法
|
|
|
|
|
|
// =============================================================================
|
2026-01-07 16:19:28 +08:00
|
|
|
|
|
2026-01-09 19:45:50 +08:00
|
|
|
|
var (
|
|
|
|
|
|
manager = GetManager()
|
|
|
|
|
|
logPool *grpool.Pool
|
|
|
|
|
|
serverName string
|
2026-01-16 16:55:32 +08:00
|
|
|
|
LogRedisKey string
|
2026-01-09 19:45:50 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2026-01-16 16:55:32 +08:00
|
|
|
|
// FieldInfo 定义字段信息结构体
|
|
|
|
|
|
type FieldInfo struct {
|
|
|
|
|
|
FieldName string
|
|
|
|
|
|
FieldValue interface{}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-09 19:45:50 +08:00
|
|
|
|
const PageSize = 20
|
|
|
|
|
|
|
|
|
|
|
|
// GetDB 获取默认数据源的数据库实例(向后兼容)
|
|
|
|
|
|
func GetDB() *mongo.Database {
|
|
|
|
|
|
source, err := manager.GetDataSource("default")
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
return source.Database()
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// =============================================================================
|
|
|
|
|
|
// MongoDB 操作方法(支持多数据源)
|
|
|
|
|
|
// =============================================================================
|
2025-12-19 15:17:19 +08:00
|
|
|
|
|
2026-01-09 19:45:50 +08:00
|
|
|
|
// getDataSource 获取当前使用的数据源
|
|
|
|
|
|
func (m *MongoDB) getDataSource() (DataSource, error) {
|
|
|
|
|
|
if m.dataSource == "" {
|
|
|
|
|
|
m.dataSource = "default"
|
2025-12-19 15:17:19 +08:00
|
|
|
|
}
|
2026-01-09 19:45:50 +08:00
|
|
|
|
return manager.GetDataSource(m.dataSource)
|
2025-11-25 11:51:16 +08:00
|
|
|
|
}
|
2026-01-06 17:01:10 +08:00
|
|
|
|
|
2026-01-16 16:55:32 +08:00
|
|
|
|
// Count 查询总数
|
|
|
|
|
|
func (m *MongoDB) Count(ctx context.Context, filter bson.M, collection string) (count int64, err error) {
|
|
|
|
|
|
source, err := m.getDataSource()
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return 0, err
|
|
|
|
|
|
}
|
|
|
|
|
|
db := source.Database()
|
|
|
|
|
|
|
|
|
|
|
|
user, err := utils.GetUserInfo(ctx)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
filter["isDeleted"] = false
|
|
|
|
|
|
delete(filter, "tenantId")
|
|
|
|
|
|
filterKey := fmt.Sprintf("%+v", filter)
|
|
|
|
|
|
redisKey := fmt.Sprintf(redis.Count, user.TenantId, collection, filterKey)
|
2026-01-21 16:33:37 +08:00
|
|
|
|
if !m.noCache {
|
2026-01-16 16:55:32 +08:00
|
|
|
|
var resultStr *gvar.Var
|
2026-01-28 10:17:03 +08:00
|
|
|
|
resultStr, err = redis.RedisClient().Get(ctx, redisKey)
|
2026-01-16 16:55:32 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
if !g.IsEmpty(resultStr) {
|
|
|
|
|
|
count = gconv.Int64(resultStr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-01-21 16:33:37 +08:00
|
|
|
|
// 如果没有调用 noTenantId,则添加 tenantId 过滤
|
|
|
|
|
|
if !m.noTenantId && !g.IsEmpty(user.TenantId) {
|
|
|
|
|
|
filter["tenantId"] = user.TenantId
|
|
|
|
|
|
}
|
2026-01-16 16:55:32 +08:00
|
|
|
|
count, err = db.Collection(collection).CountDocuments(ctx, filter)
|
2026-01-21 16:33:37 +08:00
|
|
|
|
if !m.noCache {
|
2026-01-28 10:17:03 +08:00
|
|
|
|
err = redis.RedisClient().SetEX(ctx, redisKey, count, int64(time.Hour))
|
2026-01-16 16:55:32 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-11-25 11:51:16 +08:00
|
|
|
|
// Find 查询多条记录
|
2026-01-07 16:19:28 +08:00
|
|
|
|
func (m *MongoDB) Find(ctx context.Context, filter bson.M, result interface{}, collection string, page *beans.Page, orderBy []beans.OrderBy) (total int64, err error) {
|
2026-01-09 19:45:50 +08:00
|
|
|
|
source, err := m.getDataSource()
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return 0, err
|
|
|
|
|
|
}
|
|
|
|
|
|
db := source.Database()
|
|
|
|
|
|
|
2026-01-07 17:44:15 +08:00
|
|
|
|
if err = utils.ValidStructPtr(result); err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-12-30 10:52:12 +08:00
|
|
|
|
user, err := utils.GetUserInfo(ctx)
|
2025-12-02 11:27:35 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-01-16 16:55:32 +08:00
|
|
|
|
if g.IsEmpty(filter["isDeleted"]) {
|
|
|
|
|
|
filter["isDeleted"] = false
|
|
|
|
|
|
}
|
2026-01-06 17:01:10 +08:00
|
|
|
|
filterKey := fmt.Sprintf("%+v", filter)
|
|
|
|
|
|
optionsKey := fmt.Sprintf("%+v%+v", page, orderBy)
|
|
|
|
|
|
redisKey := fmt.Sprintf(redis.List, user.TenantId, collection, filterKey, optionsKey)
|
2026-01-21 16:33:37 +08:00
|
|
|
|
if !m.noCache {
|
2025-12-29 14:46:39 +08:00
|
|
|
|
var resultStr *gvar.Var
|
2026-01-28 10:17:03 +08:00
|
|
|
|
resultStr, err = redis.RedisClient().Get(ctx, redisKey)
|
2025-12-04 17:38:34 +08:00
|
|
|
|
if err != nil {
|
2025-12-29 14:46:39 +08:00
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-01-06 17:01:10 +08:00
|
|
|
|
if !resultStr.IsEmpty() {
|
2026-01-07 16:19:28 +08:00
|
|
|
|
if err = resultStr.Structs(result); err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
total = int64(len(resultStr.Array()))
|
2025-12-29 14:46:39 +08:00
|
|
|
|
return
|
2025-12-04 17:38:34 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-01-21 16:33:37 +08:00
|
|
|
|
// 如果没有调用 noTenantId,则添加 tenantId 过滤
|
|
|
|
|
|
if !m.noTenantId && !g.IsEmpty(user.TenantId) {
|
|
|
|
|
|
filter["tenantId"] = user.TenantId
|
|
|
|
|
|
}
|
2026-01-06 17:01:10 +08:00
|
|
|
|
limit := int64(PageSize)
|
|
|
|
|
|
skip := int64(0)
|
2026-01-16 16:55:32 +08:00
|
|
|
|
if page != nil && !g.IsEmpty(page.PageNum) && !g.IsEmpty(page.PageSize) {
|
2026-01-06 17:01:10 +08:00
|
|
|
|
limit = page.PageSize
|
2026-01-07 16:19:28 +08:00
|
|
|
|
if limit == -1 {
|
2026-01-06 17:01:10 +08:00
|
|
|
|
skip = 0
|
2026-01-07 16:19:28 +08:00
|
|
|
|
} else {
|
|
|
|
|
|
skip = (page.PageNum - 1) * limit
|
2026-01-06 17:01:10 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
opt := options.Find().SetSkip(skip)
|
|
|
|
|
|
if limit != -1 {
|
|
|
|
|
|
opt.SetLimit(limit)
|
2026-01-07 16:19:28 +08:00
|
|
|
|
total, err = m.Count(ctx, filter, collection)
|
|
|
|
|
|
if err != nil || total == 0 {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-01-06 17:01:10 +08:00
|
|
|
|
}
|
|
|
|
|
|
if orderBy == nil {
|
|
|
|
|
|
opt.SetSort(bson.M{"createdAt": -1})
|
|
|
|
|
|
} else {
|
2026-01-08 19:09:47 +08:00
|
|
|
|
orderBson := bson.D{}
|
2026-01-06 17:01:10 +08:00
|
|
|
|
for _, v := range orderBy {
|
|
|
|
|
|
if v.Order == beans.Asc {
|
2026-01-09 19:45:50 +08:00
|
|
|
|
orderBson = append(orderBson, bson.E{Key: v.Field, Value: 1})
|
2026-01-06 17:01:10 +08:00
|
|
|
|
} else {
|
2026-01-09 19:45:50 +08:00
|
|
|
|
orderBson = append(orderBson, bson.E{Key: v.Field, Value: -1})
|
2026-01-06 17:01:10 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
opt.SetSort(orderBson)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
cur, err := db.Collection(collection).Find(ctx, filter, opt)
|
2025-11-25 11:51:16 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-01-07 16:19:28 +08:00
|
|
|
|
if limit == -1 {
|
|
|
|
|
|
total = int64(cur.RemainingBatchLength())
|
2026-01-06 17:01:10 +08:00
|
|
|
|
}
|
2026-01-07 16:19:28 +08:00
|
|
|
|
defer cur.Close(ctx)
|
|
|
|
|
|
if err = cur.All(ctx, result); err != nil {
|
2025-12-30 09:29:36 +08:00
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-01-21 16:33:37 +08:00
|
|
|
|
if !m.noCache {
|
2026-01-28 10:17:03 +08:00
|
|
|
|
err = redis.RedisClient().SetEX(ctx, redisKey, result, int64(time.Hour))
|
2025-12-29 14:46:39 +08:00
|
|
|
|
if err != nil {
|
2026-01-07 16:19:28 +08:00
|
|
|
|
return
|
2025-12-29 14:46:39 +08:00
|
|
|
|
}
|
2025-12-04 17:38:34 +08:00
|
|
|
|
}
|
2025-11-25 11:51:16 +08:00
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// FindOne 查询1条记录
|
2025-12-30 09:29:36 +08:00
|
|
|
|
func (m *MongoDB) FindOne(ctx context.Context, filter bson.M, result interface{}, collection string, opts ...options.Lister[options.FindOneOptions]) (err error) {
|
2026-01-09 19:45:50 +08:00
|
|
|
|
source, err := m.getDataSource()
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
db := source.Database()
|
|
|
|
|
|
|
2025-12-02 11:27:35 +08:00
|
|
|
|
if len(filter) == 0 {
|
|
|
|
|
|
err = gerror.New("缺少查询条件")
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-11-25 11:51:16 +08:00
|
|
|
|
if err = utils.ValidStructPtr(result); err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-12-30 10:52:12 +08:00
|
|
|
|
user, err := utils.GetUserInfo(ctx)
|
2025-12-02 11:27:35 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-12-04 17:38:34 +08:00
|
|
|
|
filter["isDeleted"] = false
|
2026-01-06 17:01:10 +08:00
|
|
|
|
filterKey := fmt.Sprintf("%+v", filter)
|
|
|
|
|
|
redisKey := fmt.Sprintf(redis.One, user.TenantId, collection, filterKey)
|
2026-01-21 16:33:37 +08:00
|
|
|
|
if !m.noCache {
|
2025-12-29 14:46:39 +08:00
|
|
|
|
var resultStr *gvar.Var
|
2026-01-28 10:17:03 +08:00
|
|
|
|
resultStr, err = redis.RedisClient().Get(ctx, redisKey)
|
2025-12-04 17:38:34 +08:00
|
|
|
|
if err != nil {
|
2025-12-29 14:46:39 +08:00
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
if !g.IsEmpty(resultStr) {
|
|
|
|
|
|
err = gconv.Scan(resultStr, result)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
return
|
2025-12-04 17:38:34 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-01-21 16:33:37 +08:00
|
|
|
|
// 如果没有调用 noTenantId,则添加 tenantId 过滤
|
|
|
|
|
|
if !m.noTenantId && !g.IsEmpty(user.TenantId) {
|
2025-12-29 14:46:39 +08:00
|
|
|
|
filter["tenantId"] = user.TenantId
|
|
|
|
|
|
}
|
2025-11-25 11:51:16 +08:00
|
|
|
|
cur := db.Collection(collection).FindOne(ctx, filter, opts...)
|
|
|
|
|
|
err = cur.Decode(result)
|
2025-12-04 17:38:34 +08:00
|
|
|
|
if errors.Is(err, mongo.ErrNoDocuments) {
|
2025-11-25 11:51:16 +08:00
|
|
|
|
err = nil
|
|
|
|
|
|
}
|
2026-01-21 16:33:37 +08:00
|
|
|
|
if !m.noCache {
|
2026-01-28 10:17:03 +08:00
|
|
|
|
err = redis.RedisClient().SetEX(ctx, redisKey, result, int64(time.Hour))
|
2025-12-29 14:46:39 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
2025-12-04 17:38:34 +08:00
|
|
|
|
}
|
2025-11-25 11:51:16 +08:00
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-01-09 19:45:50 +08:00
|
|
|
|
|
2026-01-16 16:55:32 +08:00
|
|
|
|
// getDeletedData 获取要删除的数据
|
|
|
|
|
|
func (m *MongoDB) getDeletedData(ctx context.Context, filter bson.M, collection string) (deletedIDs []bson.ObjectID, deletedData []bson.M, err error) {
|
|
|
|
|
|
// 查询要删除的数据
|
|
|
|
|
|
_, err = m.Find(ctx, filter, &deletedData, collection, nil, nil)
|
|
|
|
|
|
// 从查询结果中获取 _id
|
|
|
|
|
|
for _, doc := range deletedData {
|
|
|
|
|
|
deletedIDs = append(deletedIDs, doc["_id"].(bson.ObjectID))
|
|
|
|
|
|
}
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-30 18:21:50 +08:00
|
|
|
|
func (m *MongoDB) CleanRedis(ctx context.Context, filter bson.M, tenantId interface{}, collection string) (err error) {
|
2026-01-04 14:24:45 +08:00
|
|
|
|
listKeys := fmt.Sprintf(redis.CleanList, tenantId, collection)
|
2026-01-28 10:17:03 +08:00
|
|
|
|
keys, err := redis.RedisClient().Keys(ctx, listKeys)
|
2025-12-05 09:51:36 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
for _, key := range keys {
|
2026-01-28 10:17:03 +08:00
|
|
|
|
_, err = redis.RedisClient().Del(ctx, key)
|
2025-12-05 09:51:36 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-01-04 14:24:45 +08:00
|
|
|
|
countKeys := fmt.Sprintf(redis.CleanCount, tenantId, collection)
|
2026-01-28 10:17:03 +08:00
|
|
|
|
keys, err = redis.RedisClient().Keys(ctx, countKeys)
|
2025-12-05 09:51:36 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
for _, key := range keys {
|
2026-01-28 10:17:03 +08:00
|
|
|
|
_, err = redis.RedisClient().Del(ctx, key)
|
2025-12-05 09:51:36 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-12-15 18:15:23 +08:00
|
|
|
|
filter["isDeleted"] = false
|
|
|
|
|
|
delete(filter, "tenantId")
|
2026-01-06 17:01:10 +08:00
|
|
|
|
filterKey := fmt.Sprintf("%+v", filter)
|
|
|
|
|
|
oneKey := fmt.Sprintf(redis.One, tenantId, collection, filterKey)
|
2026-01-28 10:17:03 +08:00
|
|
|
|
_, err = redis.RedisClient().Del(ctx, oneKey)
|
2025-12-15 17:14:23 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-12-05 09:51:36 +08:00
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-11-25 11:51:16 +08:00
|
|
|
|
|
2026-01-16 16:55:32 +08:00
|
|
|
|
func (m *MongoDB) log(ctx context.Context, ids []bson.ObjectID, filter bson.M, collection string, data interface{}, userName, tenantId interface{}, operationType consts.OperationType) {
|
|
|
|
|
|
// 提前获取 IP 地址,避免异步任务执行时请求已结束
|
|
|
|
|
|
var ipAddress string
|
|
|
|
|
|
if request := g.RequestFromCtx(ctx); request != nil {
|
|
|
|
|
|
ipAddress = request.GetClientIp()
|
|
|
|
|
|
}
|
|
|
|
|
|
if operationType != consts.OperationInsert && operationType != consts.OperationDelete {
|
|
|
|
|
|
if !g.IsEmpty(filter["_id"]) {
|
|
|
|
|
|
objectID := filter["_id"].(*bson.ObjectID)
|
|
|
|
|
|
ids = append(ids, *objectID)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
var err error
|
|
|
|
|
|
if ids, _, err = m.getDeletedData(ctx, filter, collection); err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
log := &entity.OperationLog{
|
|
|
|
|
|
ServiceName: serverName,
|
|
|
|
|
|
Collection: collection,
|
|
|
|
|
|
CollectionID: ids,
|
|
|
|
|
|
Operation: string(operationType),
|
|
|
|
|
|
IPAddress: ipAddress,
|
|
|
|
|
|
Data: data,
|
|
|
|
|
|
}
|
|
|
|
|
|
log.Creator = userName
|
|
|
|
|
|
log.Updater = userName
|
|
|
|
|
|
now := >ime.Now().Time
|
|
|
|
|
|
log.CreatedAt = now
|
|
|
|
|
|
log.UpdatedAt = now
|
|
|
|
|
|
log.TenantId = tenantId
|
|
|
|
|
|
// 使用新的 context 进行 Redis 操作
|
|
|
|
|
|
if _, err := redis.AddToStream(ctx, LogRedisKey, log); err != nil {
|
|
|
|
|
|
glog.Error(ctx, "mongoLog-AddToStream err: %v", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Insert 插入多条记录
|
|
|
|
|
|
func (m *MongoDB) Insert(ctx context.Context, documents []interface{}, collection string, opts ...options.Lister[options.InsertManyOptions]) (ids []interface{}, err error) {
|
|
|
|
|
|
source, err := m.getDataSource()
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
}
|
|
|
|
|
|
db := source.Database()
|
|
|
|
|
|
|
|
|
|
|
|
user, err := utils.GetUserInfo(ctx)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
docs := make([]interface{}, 0, len(documents))
|
|
|
|
|
|
for _, document := range documents {
|
|
|
|
|
|
doc := gconv.Map(document)
|
|
|
|
|
|
delete(doc, "id")
|
|
|
|
|
|
if !g.IsEmpty(user.UserName) && g.IsEmpty(doc["creator"]) {
|
|
|
|
|
|
doc["creator"] = user.UserName
|
2026-01-07 18:27:43 +08:00
|
|
|
|
}
|
2026-01-16 16:55:32 +08:00
|
|
|
|
if !g.IsEmpty(user.UserName) && g.IsEmpty(doc["updater"]) {
|
|
|
|
|
|
doc["updater"] = user.UserName
|
|
|
|
|
|
}
|
|
|
|
|
|
if !g.IsEmpty(user.TenantId) && g.IsEmpty(doc["tenantId"]) {
|
|
|
|
|
|
doc["tenantId"] = user.TenantId
|
|
|
|
|
|
}
|
|
|
|
|
|
if g.IsEmpty(doc["createdAt"]) {
|
|
|
|
|
|
doc["createdAt"] = gtime.Now().Time
|
|
|
|
|
|
}
|
|
|
|
|
|
if g.IsEmpty(doc["updatedAt"]) {
|
|
|
|
|
|
doc["updatedAt"] = gtime.Now().Time
|
|
|
|
|
|
}
|
|
|
|
|
|
doc["isDeleted"] = false
|
|
|
|
|
|
docs = append(docs, doc)
|
|
|
|
|
|
}
|
|
|
|
|
|
r, err := db.Collection(collection).InsertMany(ctx, docs, opts...)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
ids = r.InsertedIDs
|
|
|
|
|
|
err = m.CleanRedis(ctx, bson.M{}, user.TenantId, collection)
|
|
|
|
|
|
//写日志
|
|
|
|
|
|
if collection != consts.OperationLogCollection {
|
|
|
|
|
|
objectIds := make([]bson.ObjectID, 0)
|
|
|
|
|
|
for _, id := range ids {
|
|
|
|
|
|
objectIds = append(objectIds, id.(bson.ObjectID))
|
2026-01-07 18:27:43 +08:00
|
|
|
|
}
|
2026-01-16 16:55:32 +08:00
|
|
|
|
m.log(ctx, objectIds, nil, collection, nil, user.UserName, user.TenantId, consts.OperationInsert)
|
|
|
|
|
|
}
|
2026-01-07 18:27:43 +08:00
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-11-25 11:51:16 +08:00
|
|
|
|
// Delete 删除记录
|
2025-12-30 09:29:36 +08:00
|
|
|
|
func (m *MongoDB) Delete(ctx context.Context, filter bson.M, collection string, opts ...options.Lister[options.DeleteManyOptions]) (count int64, err error) {
|
2026-01-09 19:45:50 +08:00
|
|
|
|
source, err := m.getDataSource()
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return 0, err
|
|
|
|
|
|
}
|
|
|
|
|
|
db := source.Database()
|
|
|
|
|
|
|
2025-11-28 17:13:16 +08:00
|
|
|
|
if len(filter) == 0 {
|
|
|
|
|
|
err = gerror.New("缺少查询条件")
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-12-30 10:52:12 +08:00
|
|
|
|
user, err := utils.GetUserInfo(ctx)
|
2025-12-02 11:27:35 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
filter["tenantId"] = user.TenantId
|
2026-01-16 16:55:32 +08:00
|
|
|
|
// 获取要删除的数据
|
|
|
|
|
|
ds, ms, err := m.getDeletedData(ctx, filter, collection)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
// 执行删除操作
|
2025-11-25 11:51:16 +08:00
|
|
|
|
r, err := db.Collection(collection).DeleteMany(ctx, filter, opts...)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
count = r.DeletedCount
|
2026-01-16 16:55:32 +08:00
|
|
|
|
// 清理redis
|
2025-12-30 18:21:50 +08:00
|
|
|
|
err = m.CleanRedis(ctx, filter, user.TenantId, collection)
|
2026-01-16 16:55:32 +08:00
|
|
|
|
// 写日志
|
|
|
|
|
|
m.log(ctx, ds, nil, collection, ms, user.UserName, user.TenantId, consts.OperationDelete)
|
2025-11-25 11:51:16 +08:00
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-16 16:55:32 +08:00
|
|
|
|
// DeleteSoft 假删除记录
|
2026-01-26 09:02:49 +08:00
|
|
|
|
func (m *MongoDB) DeleteSoft(ctx context.Context, filter bson.M, collection string, opts ...options.Lister[options.UpdateManyOptions]) (modifiedCount int64, err error) {
|
2026-01-16 16:55:32 +08:00
|
|
|
|
update := bson.M{"$set": bson.M{"isDeleted": true}}
|
|
|
|
|
|
return m.Update(ctx, filter, update, collection, opts...)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-11-25 11:51:16 +08:00
|
|
|
|
// Update 修改记录
|
2026-01-26 09:02:49 +08:00
|
|
|
|
func (m *MongoDB) Update(ctx context.Context, filter bson.M, update bson.M, collection string, opts ...options.Lister[options.UpdateManyOptions]) (modifiedCount int64, err error) {
|
2026-01-09 19:45:50 +08:00
|
|
|
|
source, err := m.getDataSource()
|
|
|
|
|
|
if err != nil {
|
2026-01-26 09:02:49 +08:00
|
|
|
|
return 0, err
|
2026-01-09 19:45:50 +08:00
|
|
|
|
}
|
|
|
|
|
|
db := source.Database()
|
|
|
|
|
|
|
2025-11-28 17:13:16 +08:00
|
|
|
|
if len(filter) == 0 {
|
|
|
|
|
|
err = gerror.New("缺少查询条件")
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-12-02 11:27:35 +08:00
|
|
|
|
filter["isDeleted"] = false
|
2025-12-30 10:52:12 +08:00
|
|
|
|
user, err := utils.GetUserInfo(ctx)
|
2025-12-02 11:27:35 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-12-26 14:02:25 +08:00
|
|
|
|
if !g.IsEmpty(user.TenantId) {
|
|
|
|
|
|
filter["tenantId"] = user.TenantId
|
|
|
|
|
|
}
|
2026-01-16 16:55:32 +08:00
|
|
|
|
// 遍历 update 中的所有操作符和字段,存放到 list 中
|
|
|
|
|
|
fieldList := make([]FieldInfo, 0)
|
|
|
|
|
|
for _, doc := range update {
|
|
|
|
|
|
if m, ok := doc.(bson.M); ok {
|
|
|
|
|
|
for fieldName, fieldValue := range m {
|
|
|
|
|
|
// 获取到字段名和字段值
|
|
|
|
|
|
fieldList = append(fieldList, FieldInfo{
|
|
|
|
|
|
FieldName: fieldName,
|
|
|
|
|
|
FieldValue: fieldValue,
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-01-23 16:36:28 +08:00
|
|
|
|
setDoc := bson.M{}
|
|
|
|
|
|
if !g.IsEmpty(update["$set"]) {
|
|
|
|
|
|
setDoc = update["$set"].(bson.M)
|
|
|
|
|
|
}
|
2025-12-26 14:02:25 +08:00
|
|
|
|
if !g.IsEmpty(user.UserName) {
|
|
|
|
|
|
setDoc["updater"] = user.UserName
|
|
|
|
|
|
}
|
2025-12-02 15:56:57 +08:00
|
|
|
|
setDoc["updatedAt"] = gtime.Now().Time
|
2026-01-16 16:55:32 +08:00
|
|
|
|
update["$set"] = setDoc
|
2026-01-26 09:02:49 +08:00
|
|
|
|
result, err := db.Collection(collection).UpdateMany(ctx, filter, update, opts...)
|
2025-11-25 11:51:16 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-01-26 09:02:49 +08:00
|
|
|
|
modifiedCount = result.ModifiedCount
|
2026-01-16 16:55:32 +08:00
|
|
|
|
// 清理redis
|
2025-12-30 18:21:50 +08:00
|
|
|
|
err = m.CleanRedis(ctx, filter, user.TenantId, collection)
|
2026-01-16 16:55:32 +08:00
|
|
|
|
// 写日志
|
|
|
|
|
|
if !g.IsEmpty(setDoc["isDeleted"]) && gconv.Bool(setDoc["isDeleted"]) {
|
|
|
|
|
|
filter["isDeleted"] = true
|
|
|
|
|
|
m.log(ctx, nil, filter, collection, nil, user.UserName, user.TenantId, consts.OperationDeleteSoft)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
m.log(ctx, nil, filter, collection, fieldList, user.UserName, user.TenantId, consts.OperationUpdate)
|
|
|
|
|
|
}
|
2025-11-25 11:51:16 +08:00
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-26 14:02:25 +08:00
|
|
|
|
// SaveOrUpdate 批量增加或修改
|
2025-12-30 09:29:36 +08:00
|
|
|
|
func (m *MongoDB) SaveOrUpdate(ctx context.Context, filter []bson.M, update []bson.M, collection string, opts ...options.Lister[options.UpdateManyOptions]) (result *mongo.BulkWriteResult, err error) {
|
2026-01-09 19:45:50 +08:00
|
|
|
|
source, err := m.getDataSource()
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
}
|
|
|
|
|
|
db := source.Database()
|
|
|
|
|
|
|
2025-12-26 14:02:25 +08:00
|
|
|
|
if len(filter) == 0 || len(update) == 0 {
|
|
|
|
|
|
err = gerror.New("缺少查询条件或更新数据")
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
if len(filter) != len(update) {
|
|
|
|
|
|
err = gerror.New("查询条件和更新数据的数量必须一致")
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-12-30 10:52:12 +08:00
|
|
|
|
user, err := utils.GetUserInfo(ctx)
|
2025-12-26 14:02:25 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-01-09 19:45:50 +08:00
|
|
|
|
|
2025-12-26 14:02:25 +08:00
|
|
|
|
var models []mongo.WriteModel
|
|
|
|
|
|
for i := 0; i < len(filter); i++ {
|
|
|
|
|
|
filter[i]["isDeleted"] = false
|
|
|
|
|
|
if !g.IsEmpty(user.TenantId) {
|
|
|
|
|
|
filter[i]["tenantId"] = user.TenantId
|
|
|
|
|
|
}
|
|
|
|
|
|
if setDoc, exists := update[i]["$set"].(bson.M); exists {
|
|
|
|
|
|
if !g.IsEmpty(user.UserName) {
|
|
|
|
|
|
setDoc["updater"] = user.UserName
|
|
|
|
|
|
}
|
|
|
|
|
|
setDoc["updatedAt"] = gtime.Now().Time
|
|
|
|
|
|
} else {
|
|
|
|
|
|
setDoc := bson.M{}
|
|
|
|
|
|
if !g.IsEmpty(user.UserName) {
|
|
|
|
|
|
setDoc["updater"] = user.UserName
|
|
|
|
|
|
}
|
|
|
|
|
|
setDoc["updatedAt"] = gtime.Now().Time
|
|
|
|
|
|
update[i]["$set"] = setDoc
|
|
|
|
|
|
}
|
|
|
|
|
|
updateModel := mongo.NewUpdateOneModel()
|
|
|
|
|
|
updateModel.SetFilter(filter[i])
|
|
|
|
|
|
updateModel.SetUpdate(update[i])
|
2026-01-09 19:45:50 +08:00
|
|
|
|
updateModel.SetUpsert(true)
|
2025-12-26 14:02:25 +08:00
|
|
|
|
if len(opts) > 0 {
|
|
|
|
|
|
for _, opt := range opts {
|
|
|
|
|
|
var updateOpts options.UpdateManyOptions
|
|
|
|
|
|
optFuncs := opt.List()
|
|
|
|
|
|
for _, fn := range optFuncs {
|
|
|
|
|
|
fn(&updateOpts)
|
|
|
|
|
|
}
|
|
|
|
|
|
if updateOpts.Upsert != nil {
|
|
|
|
|
|
updateModel.SetUpsert(*updateOpts.Upsert)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
models = append(models, updateModel)
|
|
|
|
|
|
}
|
2026-01-09 19:45:50 +08:00
|
|
|
|
|
2025-12-26 14:02:25 +08:00
|
|
|
|
bulkOpts := options.BulkWrite().SetOrdered(false)
|
|
|
|
|
|
bulkResult, err := db.Collection(collection).BulkWrite(ctx, models, bulkOpts)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
}
|
2026-01-09 19:45:50 +08:00
|
|
|
|
|
2025-12-26 14:02:25 +08:00
|
|
|
|
for _, filterItem := range filter {
|
2025-12-30 18:21:50 +08:00
|
|
|
|
err = m.CleanRedis(ctx, filterItem, user.TenantId, collection)
|
2025-12-26 14:02:25 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
glog.Warning(ctx, "清理Redis缓存失败:", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return bulkResult, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-22 15:04:13 +08:00
|
|
|
|
func BuildUpdateData(ctx context.Context, req interface{}) (filter bson.M, err error) {
|
2026-01-14 18:34:56 +08:00
|
|
|
|
_ = ctx
|
|
|
|
|
|
filter = bson.M{}
|
|
|
|
|
|
reqMap := gconv.Map(req)
|
|
|
|
|
|
for mk, mv := range reqMap {
|
|
|
|
|
|
if mk != "id" && !g.IsEmpty(mv) {
|
|
|
|
|
|
filter[mk] = mv
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|