41 lines
763 B
Go
41 lines
763 B
Go
package repo
|
|
|
|
import (
|
|
"context"
|
|
"taotie-api/core"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
type MongoDb struct {
|
|
client *mongo.Client
|
|
cfg *core.Configuration
|
|
}
|
|
|
|
// NewMongoDb 创建一个新的 MongoDb 实例
|
|
func NewMongoDb(cfg *core.Configuration) (*MongoDb, error) {
|
|
ctx := context.Background()
|
|
|
|
// 连接数据库
|
|
client, err := mongo.Connect(ctx, options.Client().ApplyURI(cfg.DB.MongoURI))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// 检查连接是否成功
|
|
err = client.Ping(ctx, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &MongoDb{
|
|
client: client,
|
|
cfg: cfg,
|
|
}, nil
|
|
}
|
|
|
|
// Db 返回数据库实例
|
|
func (m *MongoDb) Db() *mongo.Database {
|
|
return m.client.Database(m.cfg.DB.DBName)
|
|
}
|