2024-07-20 01:09:42 +00:00
|
|
|
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
|
2024-07-20 01:09:42 +00:00
|
|
|
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
|
2024-07-20 01:09:42 +00:00
|
|
|
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!")
|
|
|
|
}
|