-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongodb.go
64 lines (48 loc) · 1.5 KB
/
mongodb.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package database
import (
context "context"
fmt "fmt"
time "time"
mongo "go.mongodb.org/mongo-driver/mongo"
options "go.mongodb.org/mongo-driver/mongo/options"
Config "mLibAPI/src/config"
Helpers "mLibAPI/src/helpers"
)
const (
connectTimeout = 5
connectionStringTemplate = "mongodb://%s:%s@%s"
)
func ConnectDB() *mongo.Client {
Config.Init()
username := Config.DB_Username
password := Config.DB_Password
clusterEndpoint := Config.DB_ClusterEndpoint
connectionURI := fmt.Sprintf(connectionStringTemplate, username, password, clusterEndpoint)
client, err := mongo.NewClient(options.Client().ApplyURI(connectionURI))
Helpers.PrintError(err)
ctx, cancel := context.WithTimeout(context.Background(), connectTimeout*time.Second)
defer cancel()
err = client.Connect(ctx)
Helpers.PrintError(err)
err = client.Ping(ctx, nil)
Helpers.PrintError(err)
if Config.Mode == "DEV" {
fmt.Println("Connected to MongoDB")
}
return client
}
var DB *mongo.Client = ConnectDB()
func GetCollection(client *mongo.Client, collectionName string) *mongo.Collection {
collection := client.Database(Config.DB_Collection).Collection(collectionName)
return collection
}
// var Client, _ = mongo.NewClient(options.Client().ApplyURI(Config.DBAdress))
// var Ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
// var db = Client.Database("mo1394_lightning")
// var links = db.Collection("links")
// func Init() {
// var err = Client.Connect(Ctx)
// if err != nil {
// log.Fatal(err)
// }
// }