47 lines
1.1 KiB
Go
47 lines
1.1 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
type DatabaseController struct{
|
|
db *mongo.Database
|
|
}
|
|
|
|
func Init() *DatabaseController{
|
|
uri := os.Getenv("MONGODB_URI"); if uri == "" {
|
|
log.Fatal("You must set your 'MONGODB_URI' environmental variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/#environment-variable")
|
|
}
|
|
|
|
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri)); if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
defer func() {
|
|
if err := client.Disconnect(context.TODO()); err != nil {
|
|
panic(err)
|
|
}
|
|
}()
|
|
|
|
db := client.Database(os.Getenv("MONGODB_NAME"))
|
|
var result bson.M
|
|
|
|
db.Collection("Games").FindOne(context.TODO(), bson.D{{"name", "Card_game"}}).Decode(&result)
|
|
|
|
fmt.Println(result)
|
|
|
|
|
|
return &DatabaseController{db}
|
|
// databases, err := client.ListDatabaseNames(context.TODO(), bson.M{})
|
|
|
|
// fmt.Println(databases)
|
|
|
|
// Collection := client.Database(os.Getenv("MONGODB_NAME")).Collection("Games")
|
|
} |