I am using Mongo-driver
with gin framework. I have written code to connect mongodb in DB package and if I write query inside db/connect.go
, it works but when I use same dbcon
in other package it doesn't.
db/connect.go:
var dbcon *mongo.Database
func ConfigDB() (*mongo.Database) {
ctx := context.Background()
client, err := mongo.Connect(
ctx,
options.Client().ApplyURI("mongodb://localhost:27017/todo"),
)
if err != nil {
log.Fatal(err)
}
dbcon = client.Database("todo")
}
if I use the code below in same db/connect.go, then it works but when I use the same code in handler/task.go, then it won't.
func CreateTask() () {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
res, err := dbcon.Collection("ttest").InsertOne(ctx, bson.D{
{"task", "test4"},
{"createdAt", "test"},
{"modifiedAt","test3"},
})
if err != nil {
fmt.Println( err))
}
}
I have to implement a mongo-driver
in my project, but due to above issue I am facing problem to implement.
You'll have to import to import the db/connect.go file into the handler/task.go. This is not working because they are in different packages. In my opinion you could refactor your code like this
func ConfigDB() (*mongo.Database) {
ctx := context.Background()
client, err := mongo.Connect(
ctx,
options.Client().ApplyURI("mongodb://localhost:27017/todo"),
)
if err != nil {
log.Fatal(err)
}
return client.Database("todo")
}
import (
"db/connect"
)
func CreateTask() () {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
res, err := ConfigDB().Collection("test").InsertOne(ctx, bson.D{
{"task", "test4"},
{"createdAt", "test"},
{"modifiedAt","test3"},
})
if err != nil {
fmt.Println( err))
}
}
Here I post a complete working example. I catch the mongo session connection in a global variable. So that, anywhere in the project you can access the active connection.
package main
import (
"fmt"
"net/http"
"os"
"github.com/gin-gonic/gin"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
// SESSION ensure global mongodb connection
var SESSION *mgo.Session
func init() {
// mongodb manual connection using host ip. Replace your host IP address there
session, err := mgo.Dial("172.17.0.2")
// session, err := mgo.Dial("<HostIP>")
Must(err)
fmt.Println(err)
SESSION = session
}
func main() {
port := os.Getenv("PORT")
gin.SetMode(gin.ReleaseMode)
// gin.SetMode(gin.DebugMode)
r := gin.Default()
r.Use(mapMongo)
if port == "" {
port = "8000"
}
r.POST("/api/v1/task", CreateTask)
http.ListenAndServe(":"+port, r)
}
// close connection
func mapMongo(c *gin.Context) {
s := SESSION.Clone()
defer s.Close()
c.Set("mongo", s.DB("mongotask"))
c.Next()
}
// Must to catch the mongo panic issues
func Must(err error) {
if err != nil {
panic(err.Error())
}
}
// NewTask Struct/model
type NewTask struct {
Id bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
Task string
}
// Mongo bson generate New unique Id each request
func (self *NewTask) Init() {
self.Id = bson.NewObjectId()
}
const (
// CollectionTask is the collection name
CollectionTask = "taskCollection"
)
// CreateTask to create new Task message
func CreateTask(c *gin.Context) {
var newTask NewTask
err := c.BindJSON(&newTask)
if err != nil {
c.Error(err)
return
}
mongodb := c.MustGet("mongo").(*mgo.Database)
con := mongodb.C(CollectionTask)
// fmt.Println(newTask)
con.Insert(newTask)
if err != nil {
c.Error(err)
}
}