更新
This commit is contained in:
@@ -30,13 +30,19 @@ func GetDB() *mongo.Database {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
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)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
mongoAddr := g.Cfg().MustGet(context.Background(), "mongo.address").String()
|
|
||||||
opt := options.Client().ApplyURI(mongoAddr)
|
opt := options.Client().ApplyURI(mongoAddr)
|
||||||
client, err := mongo.Connect(opt)
|
client, err := mongo.Connect(opt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
glog.Error(ctx, "mongodb连接失败", err)
|
glog.Error(ctx, "mongodb连接失败", err)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
// 从连接串中解析数据库名
|
// 从连接串中解析数据库名
|
||||||
dbName := gstr.SubStr(mongoAddr, strings.LastIndex(mongoAddr, "/")+1, len(mongoAddr))
|
dbName := gstr.SubStr(mongoAddr, strings.LastIndex(mongoAddr, "/")+1, len(mongoAddr))
|
||||||
@@ -45,6 +51,7 @@ func init() {
|
|||||||
dbName = gstr.SubStr(dbName, 0, strings.Index(dbName, "?"))
|
dbName = gstr.SubStr(dbName, 0, strings.Index(dbName, "?"))
|
||||||
}
|
}
|
||||||
db = client.Database(dbName)
|
db = client.Database(dbName)
|
||||||
|
glog.Info(ctx, "✅ MongoDB 初始化成功")
|
||||||
}
|
}
|
||||||
func listOptionsToMap(ctx context.Context, opts ...options.Lister[options.FindOptions]) (m map[string]interface{}) {
|
func listOptionsToMap(ctx context.Context, opts ...options.Lister[options.FindOptions]) (m map[string]interface{}) {
|
||||||
// 输出opts参数中的值
|
// 输出opts参数中的值
|
||||||
|
|||||||
Reference in New Issue
Block a user