41 lines
834 B
Go
41 lines
834 B
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"time"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
func DBinstance() *mongo.Client {
|
|
mongoURI := "mongodb://localhost:27017"
|
|
fmt.Printf("Connecting to mongodb: %v\n", mongoURI)
|
|
|
|
client, err := mongo.NewClient(options.Client().ApplyURI(mongoURI))
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
err = client.Connect(ctx)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
fmt.Println("connected to mongodb")
|
|
return client
|
|
}
|
|
|
|
var Client *mongo.Client = DBinstance()
|
|
|
|
func OpenCollection(client *mongo.Client, collectionName string) *mongo.Collection {
|
|
var collection *mongo.Collection = client.Database("restaurant").Collection(collectionName)
|
|
|
|
return collection
|
|
}
|