1
This commit is contained in:
75
dao/mongo_dao.go
Normal file
75
dao/mongo_dao.go
Normal file
@@ -0,0 +1,75 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user