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.