首页 > 解决方案 > 如何使用 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,但由于上述问题,我面临实施问题。

标签: gogo-gin

解决方案


您必须导入才能将 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))
    }
}

推荐阅读