Files
customer-server/dao/mongo_dao.go
2026-03-14 10:02:49 +08:00

76 lines
2.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package dao
import (
"context"
commonMongo "gitea.com/red-future/common/db/mongo"
"go.mongodb.org/mongo-driver/v2/bson"
)
// MongoDAO MongoDB原生查询不需要token验证
var MongoDAO = new(mongoDAO)
type mongoDAO struct{}
// FindOne 原生查询单条记录不需要token验证
// 未找到记录时返回 nil error调用方需检查 result 是否为零值
func (m *mongoDAO) FindOne(ctx context.Context, filter bson.M, result interface{}, collectionName string) error {
db := commonMongo.GetDB()
collection := db.Collection(collectionName)
err := collection.FindOne(ctx, filter).Decode(result)
if err != nil {
if err.Error() == "mongo: no documents in result" {
return nil // 未找到记录返回nil而不是错误
}
return err
}
return nil
}
// InsertOne 原生插入单条记录不需要token验证
func (m *mongoDAO) InsertOne(ctx context.Context, document interface{}, collectionName string) (interface{}, error) {
db := commonMongo.GetDB()
collection := db.Collection(collectionName)
result, err := collection.InsertOne(ctx, document)
if err != nil {
return nil, err
}
return result.InsertedID, nil
}
// UpdateOne 原生更新单条记录不需要token验证
// 返回 matchedCount匹配到的记录数和 modifiedCount实际修改的记录数
func (m *mongoDAO) UpdateOne(ctx context.Context, filter bson.M, update bson.M, collectionName string) (matchedCount int64, modifiedCount int64, err error) {
db := commonMongo.GetDB()
collection := db.Collection(collectionName)
result, err := collection.UpdateOne(ctx, filter, update)
if err != nil {
return 0, 0, err
}
return result.MatchedCount, result.ModifiedCount, nil
}
// UpdateMany 原生批量更新记录不需要token验证
func (m *mongoDAO) UpdateMany(ctx context.Context, filter bson.M, update bson.M, collectionName string) (matchedCount int64, modifiedCount int64, err error) {
db := commonMongo.GetDB()
collection := db.Collection(collectionName)
result, err := collection.UpdateMany(ctx, filter, update)
if err != nil {
return 0, 0, err
}
return result.MatchedCount, result.ModifiedCount, nil
}
// Delete 原生删除记录不需要token验证用于回滚操作
func (m *mongoDAO) Delete(ctx context.Context, filter bson.M, collectionName string) error {
db := commonMongo.GetDB()
collection := db.Collection(collectionName)
_, err := collection.DeleteOne(ctx, filter)
return err
}