mirror of
https://github.com/0ceanSlim/grain.git
synced 2024-10-30 01:26:32 +00:00
34 lines
703 B
Go
34 lines
703 B
Go
|
package db
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
|
||
|
"go.mongodb.org/mongo-driver/mongo"
|
||
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||
|
)
|
||
|
|
||
|
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
|
||
|
}
|
||
|
|
||
|
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!")
|
||
|
}
|