Files
billai/server/database/mongo.go
CHE LIANG ZHAO 3b7c1cd82b chore(release): v1.0.7
- README/CHANGELOG: add v1.0.7 entry\n- Server: JWT expiry validated server-side (401 codes)\n- Web: logout/redirect on 401; proxy forwards Authorization\n- Server: bill service uses repository consistently
2026-01-16 11:15:05 +08:00

72 lines
1.8 KiB
Go

package database
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"billai-server/config"
)
var (
// Client MongoDB 客户端实例
Client *mongo.Client
// DB 数据库实例
DB *mongo.Database
// RawBillCollection 原始账单数据集合
RawBillCollection *mongo.Collection
// CleanedBillCollection 清洗后账单数据集合
CleanedBillCollection *mongo.Collection
)
// Connect 连接 MongoDB
func Connect() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// 创建客户端选项
clientOptions := options.Client().ApplyURI(config.Global.MongoURI)
// 连接 MongoDB
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
return fmt.Errorf("连接 MongoDB 失败: %w", err)
}
// 测试连接
if err := client.Ping(ctx, nil); err != nil {
return fmt.Errorf("MongoDB Ping 失败: %w", err)
}
// 设置全局变量
Client = client
DB = client.Database(config.Global.MongoDatabase)
RawBillCollection = DB.Collection(config.Global.MongoRawCollection)
CleanedBillCollection = DB.Collection(config.Global.MongoCleanedCollection)
fmt.Printf("🍃 MongoDB 连接成功: %s\n", config.Global.MongoDatabase)
fmt.Printf(" 📄 原始数据集合: %s\n", config.Global.MongoRawCollection)
fmt.Printf(" 📄 清洗数据集合: %s\n", config.Global.MongoCleanedCollection)
return nil
}
// Disconnect 断开 MongoDB 连接
func Disconnect() error {
if Client == nil {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := Client.Disconnect(ctx); err != nil {
return fmt.Errorf("断开 MongoDB 连接失败: %w", err)
}
fmt.Println("🍃 MongoDB 连接已断开")
return nil
}