-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.go
46 lines (35 loc) · 942 Bytes
/
db.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
package gah
import (
"context"
"log"
"os"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// Mongodb env variables
const (
MongoUrlKey = "MONGO_URL"
MongoDatabaseKey = "MONGO_DATABASE"
MongoUsersCollectionkey = "MONGO_COLLECTION"
)
// Mongo returns the client required to connect.
func getClient() *mongo.Client {
mongoUrl := os.Getenv(MongoUrlKey)
clientOptions := options.Client().ApplyURI(mongoUrl)
client, err := mongo.NewClient(clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Connect(context.Background())
if err != nil {
log.Fatal(err)
}
return client
}
// GetCollection This is the solution to use collections.
func GetCollection() *mongo.Collection {
dbName := os.Getenv(MongoDatabaseKey)
collectionName := os.Getenv(MongoUsersCollectionkey)
collection := getClient().Database(dbName).Collection(collectionName)
return collection
}