You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
dingtalk/vendor/go.dtapp.net/dorm/mongo.go

63 lines
1.4 KiB

2 years ago
package dorm
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
2 years ago
// MongoClientFun *MongoClient 驱动
// string 库名
type MongoClientFun func() (*MongoClient, string)
// MongoClientCollectionFun *MongoClient 驱动
// string 库名
// string 集合
type MongoClientCollectionFun func() (*MongoClient, string, string)
2 years ago
type ConfigMongoClient struct {
Dns string // 地址
Opts *options.ClientOptions
DatabaseName string // 库名
}
type MongoClient struct {
2 years ago
Db *mongo.Client // 驱动
config *ConfigMongoClient // 配置
2 years ago
}
func NewMongoClient(config *ConfigMongoClient) (*MongoClient, error) {
2 years ago
var ctx = context.Background()
2 years ago
var err error
c := &MongoClient{config: config}
// 连接到MongoDB
if c.config.Dns != "" {
2 years ago
c.Db, err = mongo.Connect(ctx, options.Client().ApplyURI(c.config.Dns))
2 years ago
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
} else {
2 years ago
c.Db, err = mongo.Connect(ctx, c.config.Opts)
2 years ago
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
}
// 检查连接
2 years ago
err = c.Db.Ping(ctx, nil)
2 years ago
if err != nil {
return nil, errors.New(fmt.Sprintf("检查连接失败:%v", err))
}
return c, nil
}
// Close 关闭
2 years ago
func (c *MongoClient) Close(ctx context.Context) error {
return c.Db.Disconnect(ctx)
2 years ago
}