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.
gomongo/app.go

56 lines
1.3 KiB

2 years ago
package gomongo
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
2 years ago
const Version = "1.0.7"
2 years ago
2 years ago
type Client struct {
Db *mongo.Client // 驱动
2 years ago
Dns string // 连接地址
2 years ago
DatabaseName string // 库名
2 years ago
collectionName string // 表名
}
2 years ago
// NewClient 实例化并链接数据库
func NewClient(dns string, databaseName string) *Client {
2 years ago
// 连接到MongoDB
db, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(dns))
if err != nil {
panic(fmt.Sprintf("数据库【mongo】连接失败%v", err))
}
// 检查连接
err = db.Ping(context.TODO(), nil)
if err != nil {
panic(fmt.Sprintf("数据库【mongo】连接服务器失败%v", err))
}
2 years ago
if databaseName == "" {
return &Client{Db: db, Dns: dns}
}
return &Client{Db: db, Dns: dns, DatabaseName: databaseName}
2 years ago
}
// NewDb 实例化并传入链接
2 years ago
func NewDb(db *mongo.Client, databaseName string) *Client {
if databaseName == "" {
return &Client{Db: db}
}
return &Client{Db: db, DatabaseName: databaseName}
2 years ago
}
// Close 关闭
2 years ago
func (c *Client) Close() {
err := c.Db.Disconnect(context.TODO())
2 years ago
if err != nil {
panic(errors.New(fmt.Sprintf("数据库【mongo】关闭失败%v", err)))
}
return
}