mongodb - 连接(本地主机:27017 [-4])未能写入:上下文已取消
问题描述
在这里我读到有必要取消上下文。这就是我的db.go
样子:
package db
import (
"context"
"fmt"
"log"
"os"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
connectionStringTemplate = "mongodb://%s:%s@%s"
)
var DB *mongo.Client
var Ctx context.Context
// Connect with create the connection to MongoDB
func Connect() {
username := os.Getenv("MONGODB_USERNAME")
password := os.Getenv("MONGODB_PASSWORD")
clusterEndpoint := os.Getenv("MONGODB_ENDPOINT")
connectionURI := fmt.Sprintf(connectionStringTemplate, username, password, clusterEndpoint)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.NewClient(options.Client().ApplyURI(connectionURI))
if err != nil {
log.Printf("Failed to create client: %v", err)
}
err = client.Connect(ctx)
if err != nil {
log.Printf("Failed to connect to cluster: %v", err)
}
// Force a connection to verify our connection string
err = client.Ping(ctx, nil)
if err != nil {
log.Printf("Failed to ping cluster: %v", err)
}
DB = client
Ctx = ctx
log.Printf("Connected to MongoDB!")
}
我在以下执行此操作main.go
:
func main() {
// Configure
db.Connect()
defer db.DB.Disconnect(context.Background())
r := gin.Default()
// Routes
//r.GET("/movies", handlers.GetAllMoviesHandler)
r.POST("/movies", handlers.AddMovieHandler)
// listen and serve on 0.0.0.0:8080
r.Run()
}
如果我的本地 mongodb 正在运行,它工作正常。现在当我像这样使用客户端时(我知道命名仍然不好):
func AddMovie(movie *Movie) (primitive.ObjectID, error) {
movie.ID = primitive.NewObjectID()
result, err := db.DB.Database("movies").Collection("movies").InsertOne(db.Ctx, movie)
if err != nil {
log.Printf("Could not create movie: %v", err)
return primitive.NilObjectID, err
}
oid := result.InsertedID.(primitive.ObjectID)
return oid, nil
}
我收到这样的错误
{"msg":{"Code":0,"Message":"connection(localhost:27017[-4]) failed to write: context canceled","Labels":["NetworkError","RetryableWriteError"],"Name":"","Wrapped":{"ConnectionID":"localhost:27017[-4]","Wrapped":{}}}}
当我发表评论时它工作正常,defer cancel()
但我想这不正确?我在这里做错了什么。
更新:
它在我使用时有效:
result, err :=db.DB.Database("movies").Collection("movies").InsertOne(context.Background(), movie)
而不是 ctx. 我不完全理解这些用例中上下文的用法。我也不确定是否应该Ctx = ctx
在 Connect 函数中执行。
解决方案
推荐阅读
- javascript - 如何检查 a href 是否包含 aria-current。如果为 true,则对父级和兄弟级执行代码。使用 jQuery
- chart.js - chart.js - 轴标签
- javafx - 箭头键的Javafx TableView滚动问题
- css - 使用纯 CSS 切换表格单元格
- java - Scene Builder (JavaFx) 中的错误切换场景
- python - 如何生成具有 99% 概率值落入 (3, 9) 排他性的随机值?
- python - Keras 后端函数,仅当值介于 a 和 b 之间时才给出
- python - 使用 df.head() 循环
- java - 我正在尝试将 java 对象发布到 .net 核心 web api。但我需要在 java 中发布对象数组
- javascript - 如何使用 Javascript 将 22:00:00 转换为 10 PM 或 22:00?