go - 如何使用 mongo-driver 连接到其他包
问题描述
我正在使用Mongo-driver
杜松子酒框架。我已经编写了在 DB 包中连接 mongodb 的代码,如果我在里面编写查询db/connect.go
,它可以工作,但是当我dbcon
在其他包中使用它时它不会。
分贝/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
在我的项目中实施 a,但由于上述问题,我面临实施问题。
解决方案
您必须导入才能将 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))
}
}
推荐阅读
- java - 当值为日期时,如何使用 Java 在 JSON 字符串中添加引号
- python - 当光标在它上面时,如何在kivy上为按钮设置动画?
- python - 对浮点的任何使用都失败
- wordpress - 用于 asp.net core mvc azure web 应用程序的 Wordpress 登录页面
- download - 如何让客户端的音频文件下载而不是播放?
- arm - 寄存器 15 中的程序计数器如何暴露流水线?
- rest - 使用 Kubernetes 来提高 REST API 调用的性能
- python - 当前生成器值可以与之前生成的值交互吗?
- ajax - 应用 Ajax (Codeigniter)
- r - 列出 R 中 Dropbox 文件夹中的所有文件(以便可以读取它们)