feat: server connect mongo

This commit is contained in:
CHE LIANG ZHAO
2026-01-08 23:42:01 +08:00
parent ccd2d0386a
commit c1ffe2e822
17 changed files with 1455 additions and 338 deletions

72
server/database/mongo.go Normal file
View File

@@ -0,0 +1,72 @@
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
}