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

How to use mongo-driver connection into other packages

我正在使用 Mongo-driver 和 gin 框架。我已经在 DB 包中编写了连接 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))
    }
}

这里我post一个完整的工作示例。 我在全局变量中捕获了 mongo 会话连接。这样,您可以在项目的任何位置访问活动连接。

package main

import (
    "fmt"
    "net/http"
    "os"

    "github.com/gin-gonic/gin"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

// SESSION ensure global mongodb connection
var SESSION *mgo.Session

func init() {
    // mongodb manual connection using host ip. Replace your host IP address there
    session, err := mgo.Dial("172.17.0.2")
    // session, err := mgo.Dial("<HostIP>")
    Must(err)
    fmt.Println(err)
    SESSION = session
}

func main() {

    port := os.Getenv("PORT")
    gin.SetMode(gin.ReleaseMode)
    // gin.SetMode(gin.DebugMode)
    r := gin.Default()
    r.Use(mapMongo)

    if port == "" {
        port = "8000"
    }
    r.POST("/api/v1/task", CreateTask)

    http.ListenAndServe(":"+port, r)

}

// close connection
func mapMongo(c *gin.Context) {
    s := SESSION.Clone()
    defer s.Close()
    c.Set("mongo", s.DB("mongotask"))
    c.Next()
}

// Must to catch the mongo panic issues
func Must(err error) {
    if err != nil {
        panic(err.Error())
    }
}

// NewTask Struct/model
type NewTask struct {
    Id   bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
    Task string
}

// Mongo bson generate New unique Id each request
func (self *NewTask) Init() {
    self.Id = bson.NewObjectId()
}

const (
    // CollectionTask is the collection name
    CollectionTask = "taskCollection"
)

// CreateTask to create new Task message
func CreateTask(c *gin.Context) {
    var newTask NewTask
    err := c.BindJSON(&newTask)
    if err != nil {
        c.Error(err)
        return
    }
    mongodb := c.MustGet("mongo").(*mgo.Database)
    con := mongodb.C(CollectionTask)
    // fmt.Println(newTask)
    con.Insert(newTask)
    if err != nil {
        c.Error(err)
    }

}