forked from UTDNebula/api-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.go
More file actions
56 lines (44 loc) · 1.15 KB
/
database.go
File metadata and controls
56 lines (44 loc) · 1.15 KB
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
/*
This file is responsible for providing various useful database functions.
*/
package uploader
import (
//"go.mongodb.org/mongo-driver/bson"
//"go.mongodb.org/mongo-driver/bson/primitive"
"context"
"log"
"os"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func connectDB() *mongo.Client {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
opts := options.Client().ApplyURI(getEnvMongoURI())
client, err := mongo.Connect(ctx, opts)
if err != nil {
log.Panic("Unable to create MongoDB client and connect to database")
os.Exit(1)
}
//ping the database
err = client.Ping(ctx, nil)
if err != nil {
log.Panic("Unable to ping database")
os.Exit(1)
}
log.Println("Connected to MongoDB")
return client
}
func getCollection(client *mongo.Client, collectionName string) *mongo.Collection {
collection := client.Database("combinedDB").Collection(collectionName)
return collection
}
func getEnvMongoURI() string {
uri, exist := os.LookupEnv("MONGODB_URI")
if !exist {
log.Panic("Error loading 'MONGODB_URI' from the .env file")
os.Exit(1)
}
return uri
}