我正在使用Mongo-driver
gin框架。我已经写了代码在数据库包中连接mongodb,如果我在里面编写查询db/connect.go
,它可以工作,但是当我dbcon
在其他包中使用它时却不能。
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")
}
如果我在同一个db / connect.go中使用下面的代码,则它可以工作,但是当我在handler / task.go中使用相同的代码时,则不会。
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))
}
}
我必须mongo-driver
在我的项目中实施,但是由于上述问题,我面临实施的困难。
您必须先导入才能将db / connect.go文件导入到handler / task.go中。这是行不通的,因为它们位于不同的程序包中。我认为您可以像这样重构代码
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))
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句