1
0
mirror of https://github.com/Uttkarsh-raj/Plannerly.git synced 2025-11-29 21:57:34 +02:00
Files
Plannerly/Backend/database/databaseConn.go
Uttkarsh-raj f6219f08b8 env
2023-11-07 16:40:12 +05:30

42 lines
906 B
Go

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"
)
func DBInstance() *mongo.Client {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading env file")
}
MongoDb := os.Getenv("MONGODB_URL")
log.Printf(MongoDb)
client, err := mongo.NewClient(options.Client().ApplyURI(MongoDb))
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDb")
return client
}
var Client *mongo.Client = DBInstance()
func OpenCollection(client *mongo.Client, collectionName string) *mongo.Collection {
var collection *mongo.Collection = client.Database("cluster0").Collection(collectionName)
return collection
}