init: taotie-api 项目初始化
This commit is contained in:
40
repo/mongodb.go
Normal file
40
repo/mongodb.go
Normal file
@@ -0,0 +1,40 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user