This commit is contained in:
Cold
2025-12-16 18:00:16 +08:00
committed by 张斌
parent e22f7373e6
commit f130c230e8

View File

@@ -30,13 +30,19 @@ func GetDB() *mongo.Database {
}
func init() {
// 按需初始化:没有配置 mongo.address 则跳过
mongoAddr := g.Cfg().MustGet(context.Background(), "mongo.address").String()
if mongoAddr == "" {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
mongoAddr := g.Cfg().MustGet(context.Background(), "mongo.address").String()
opt := options.Client().ApplyURI(mongoAddr)
client, err := mongo.Connect(opt)
if err != nil {
glog.Error(ctx, "mongodb连接失败", err)
return
}
// 从连接串中解析数据库名
dbName := gstr.SubStr(mongoAddr, strings.LastIndex(mongoAddr, "/")+1, len(mongoAddr))
@@ -45,6 +51,7 @@ func init() {
dbName = gstr.SubStr(dbName, 0, strings.Index(dbName, "?"))
}
db = client.Database(dbName)
glog.Info(ctx, "✅ MongoDB 初始化成功")
}
func listOptionsToMap(ctx context.Context, opts ...options.Lister[options.FindOptions]) (m map[string]interface{}) {
// 输出opts参数中的值