doufutao4428 2019-07-10 12:36
浏览 53
已采纳

如何使用mongo-driver连接到其他软件包

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.

  • 写回答

2条回答 默认 最新

  • duanbaque4230 2019-07-10 16:24
    关注

    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))
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog