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 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错