first commit
This commit is contained in:
commit
ca8c886763
11 files changed
+974
No files matched your search
@@ -0,0 +1,46 @@
|
||||
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 {
|
||||
godotenv.Load(".env")
|
||||
mongoURI := os.Getenv("mongoURI")
|
||||
|
||||
fmt.Printf("Connecting to mongodb: %v\n", mongoURI)
|
||||
|
||||
client, err := mongo.NewClient(options.Client().ApplyURI(mongoURI))
|
||||
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 {
|
||||
godotenv.Load(".env")
|
||||
dbo := os.Getenv("dbo")
|
||||
var collection *mongo.Collection = client.Database(dbo).Collection(collectionName)
|
||||
|
||||
return collection
|
||||
}
|
||||
Reference in new issue
Block a user