forked from jeffthorne/tasky
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
37 lines (31 loc) · 817 Bytes
/
database.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
package database
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var Client *mongo.Client = CreateMongoClient()
func CreateMongoClient() *mongo.Client {
godotenv.Overload()
MongoDbURI := os.Getenv("MONGODB_URI")
client, err := mongo.NewClient(options.Client().ApplyURI(MongoDbURI))
if err != nil {
log.Fatal(err)
}
var ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer cancel()
fmt.Println("Connected to MONGO -> ", MongoDbURI)
return client
}
func OpenCollection(client *mongo.Client, collectionName string) *mongo.Collection {
return client.Database("go-mongodb").Collection(collectionName)
}