遇到问题时连接到 mongodb 数据库的函数
时间:2024-03-23
浏览:113
作者:佚名
在连接到 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()
}解决方案
您在 main() 启动之前初始化连接,因此如果您在 main() 开始运行后还调用 connection() 函数,它将执行两次。但是,您的 connection 函数在从函数返回之前断开连接,根据文档,这将与数据库断开连接。目前尚不清楚断开连接后重用客户端是否会重新连接。无论如何,在返回函数之前不要断开连接。
package funtion
import (
"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 bd
func 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)
}本篇关于《遇到问题时连接到 mongodb 数据库的函数》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.28
11.28
热门专题
