From f130c230e839519eae3000e49ea2cde0de232026 Mon Sep 17 00:00:00 2001 From: Cold <16419454+cold502@user.noreply.gitee.com> Date: Tue, 16 Dec 2025 18:00:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mongo/mongo.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/mongo/mongo.go b/mongo/mongo.go index d0fd7f0..394cec0 100644 --- a/mongo/mongo.go +++ b/mongo/mongo.go @@ -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参数中的值