-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
53 lines (41 loc) · 906 Bytes
/
config.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
package main
import (
"context"
"fmt"
"log"
"os"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
mongoClient *mongo.Client
dbName = "quiz_db"
)
func ConnectToDB() *mongo.Client {
uri := "mongodb://localhost:27017"
clientOptions := options.Client().ApplyURI(uri)
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
fmt.Println("Connected to MongoDB!")
mongoClient = client
return client
}
func GetQuizCollection() *mongo.Collection {
if mongoClient == nil {
ConnectToDB()
}
return mongoClient.Database(dbName).Collection("quizzes")
}
func GetParticipantCollection() *mongo.Collection {
if mongoClient == nil {
ConnectToDB()
}
return mongoClient.Database(dbName).Collection("participants")
}