got a JSON response from the database
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo/options"
|
||||
)
|
||||
|
||||
func Connect() *mongo.Client {
|
||||
err := godotenv.Load(".env")
|
||||
if err != nil {
|
||||
log.Fatal("Unable to find or read .env file in db Connect")
|
||||
}
|
||||
|
||||
MongoDb := os.Getenv("DATABASE_URI")
|
||||
if MongoDb == "" {
|
||||
log.Fatal("DATABASE_URI not set")
|
||||
}
|
||||
fmt.Println("Database URI: ", MongoDb)
|
||||
|
||||
clientOptions := options.Client().ApplyURI(MongoDb)
|
||||
client, err := mongo.Connect(clientOptions)
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to connect: %v", err)
|
||||
}
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
var Client *mongo.Client = Connect()
|
||||
|
||||
func OpenCollection(collectionName string) *mongo.Collection {
|
||||
err := godotenv.Load(".env")
|
||||
if err != nil {
|
||||
log.Fatal("Unable to find or read .env file in OpenCollection")
|
||||
}
|
||||
|
||||
databaseName := os.Getenv("DATABASE_NAME")
|
||||
if databaseName == "" {
|
||||
log.Fatal("DATABASE_NAME not set")
|
||||
}
|
||||
fmt.Println("Database name: ", databaseName)
|
||||
|
||||
collection := Client.Database(databaseName).Collection(collectionName)
|
||||
if collection == nil {
|
||||
log.Fatal("Unable to OpenCollection")
|
||||
return nil
|
||||
}
|
||||
|
||||
return collection
|
||||
}
|
||||
Reference in New Issue
Block a user