gpt4 book ai didi

mongodb - 本地 db driver 连接 MongoDB 失败

转载 作者:行者123 更新时间:2023-12-01 22:11:23 25 4
gpt4 key购买 nike

我正在尝试通过 native MongoDB 驱动程序与 go 语言连接 MongoDB
(ref)。
这是我的快照代码。

package main

import (
"context"
"fmt"
"log"
"time"

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

const (
account = "rootAdmin"
password = "12345678"
iP = "127.0.0.1"
port = 27017
tlsCertificateKeyFile = "D:/cert/wa.pem"
)

type mongoStuff struct {
ctx context.Context
client *mongo.Client
cancel context.CancelFunc
}

func connectToMongoDB() *mongoStuff {
uri := fmt.Sprintf("mongodb://%v:%v@%v:%v/?authSource=admin&tlsCertificateKeyFile=%v&tls=true",
account,
password,
iP,
port,
tlsCertificateKeyFile)
credential := options.Credential{
AuthMechanism: "MONGODB-X509",
Username: account,
Password: password,
}
log.Println(uri)
clientOpts := options.Client().ApplyURI(uri).SetAuth(credential)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, clientOpts)
if err != nil {
log.Println("Dead connect")
log.Fatal(err)
}
return &mongoStuff{ctx, client, cancel}
}

func disconnectMongoDB(mongodb *mongoStuff) {
cancel := mongodb.cancel
client := mongodb.client
ctx := mongodb.ctx
defer cancel()
defer func() {
if err := client.Disconnect(ctx); err != nil {
log.Println("Dead disconnect")
panic(err)
}
}()
}

func insertExamples(mongodb *mongoStuff) {
ctx := mongodb.ctx
var db *mongo.Database = mongodb.client.Database("documentation_examples")
coll := db.Collection("inventory_insert")
err := coll.Drop(ctx)
if err != nil {
log.Println("Dead drop")
log.Fatal(err)
}
{
result, err := coll.InsertOne(
ctx,
bson.D{
{"item", "canvas"},
{"qty", 100},
{"tags", bson.A{"cotton"}},
{
"size", bson.D{
{"h", 28},
{"w", 35.5},
{"uom", "cm"},
}},
})
if err != nil {
log.Println("Dead insertone")
log.Fatal(err)
}
log.Printf("insertone success. id=%v", result.InsertedID)
}
}

func main() {
mongodb := connectToMongoDB()
defer disconnectMongoDB(mongodb)
insertExamples(mongodb)
}
每当我运行代码时,它都会出现以下错误。

connection() error occured during connection handshake: auth error: round trip error: (AuthenticationFailed) No user name provided


我不知道发生了什么事。

最佳答案

要使用 x.509 进行身份验证,用户名应该是证书的通用名称或为空。您似乎正在尝试混合使用密码和 x.509 身份验证。
可以在 URI 中提供所有必需的选项。见 How can I connect with X509 by putting all options in the connection string in node.js driver for mongodb? .
如果您坚持不在 URI 中指定凭据,请参阅描述如何为 x509 凭据执行此操作的驱动程序文档。

关于mongodb - 本地 db driver 连接 MongoDB 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63449304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com