grain/db/db.go

36 lines
759 B
Go
Raw Normal View History

package db
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
2024-07-20 12:41:47 +00:00
// Initialize MongoDB client
func InitDB(uri, database string) (*mongo.Client, error) {
clientOptions := options.Client().ApplyURI(uri)
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
return nil, err
}
// Check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
return nil, err
}
fmt.Println("Connected to MongoDB!")
return client, nil
}
2024-07-20 12:41:47 +00:00
// Disconnect from MongoDB
func DisconnectDB(client *mongo.Client) {
if err := client.Disconnect(context.TODO()); err != nil {
fmt.Println("Error disconnecting from MongoDB:", err)
}
fmt.Println("Disconnected from MongoDB!")
}