猿问

执行将我连接到 mongodb 数据库的函数时出现问题

我正在尝试连接到mongodb,它确实可以,但是我有一个问题,那就是当我发送日志显示连接是否成功时,消息执行了两次,我不知道这是正常的还是我的代码有问题,谢谢你的帮助。


package connection


import (

    "context"

    "log"

    "time"


    "go.mongodb.org/mongo-driver/mongo"

    "go.mongodb.org/mongo-driver/mongo/options"

    "go.mongodb.org/mongo-driver/mongo/readpref"

)


// Client es la instancia de la conexion

var Client = Connection()


// Connection es la funcion que me permite conectarme a mongodb

func Connection() *mongo.Client {

    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)

    defer cancel()

    client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))


    defer func() {

        if err = client.Disconnect(ctx); err != nil {

            panic(err.Error())

        }

    }()


    err = client.Ping(ctx, readpref.Primary())

    if err != nil {

        log.Fatal(err.Error())

    }


    log.Println("conexion exitosa a mongodb")


    return client

}

这是我的主要文件


package main


import (

    "github.com/HamelBarrer/api-go/connection"

)


func main() {

    connection.Connection()

}


拉丁的传说
浏览 126回答 2
2回答

守着星空守着你

您在 main() 开始之前初始化连接,因此如果您还在Connection()main() 开始运行后调用函数,它将执行两次。但是,您的Connection函数在从函数返回之前断开连接,根据文档,它将与数据库断开连接。目前尚不清楚在断开连接后重用客户端是否会重新连接。无论如何,在返回函数之前不要断开连接。

ABOUTYOU

package funtionimport (    "context"    "encoding/json"    "log"    "net/http"    "github.com/HamelBarrer/api-go/connection"    "github.com/HamelBarrer/api-go/models")// CreateUser es la funcion para crear en la bdfunc CreateUser(w http.ResponseWriter, r *http.Request) {    w.Header().Set("Content-Type", "application/json")    collection := connection.Client.Database("testing").Collection("numbers")    var user models.User    err := json.NewDecoder(r.Body).Decode(&user)    if err != nil {        log.Fatal(err.Error())    }    insertResult, err := collection.InsertOne(context.TODO(), user)    if err != nil {        log.Fatal(err.Error())    }    json.NewEncoder(w).Encode(insertResult.InsertedID)}
随时随地看视频慕课网APP

相关分类

Go
我要回答