gpt4 book ai didi

mongodb - mongodb无法在Go中执行事务,并且总是得到无法在多文档事务中创建 namespace

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

我正在尝试创建一个通过包装事务处理InsertOne数据的函数,并且我也已经在mongodb中设置了副本集,我在本地和MongoDB map 集中尝试了错误相同的情况,
这是代码:

    const MONGODB_URI = "mongodb://localhost:27017,localhost:27018,localhost:27019/?replicaSet=rs"
ctx := context.Background()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(MONGODB_URI))
if err != nil {
panic(err)
}

db := client.Database("production")
defer db.Client().Disconnect(ctx)
col := db.Collection("people")

// transaction
err = db.Client().UseSession(ctx, func(sessionContext mongo.SessionContext) error {
err := sessionContext.StartTransaction()
if err != nil {
fmt.Println(err)
return err
}

_, err = col.InsertOne(sessionContext, req)
if err != nil {
sessionContext.AbortTransaction(sessionContext)
fmt.Println(err)
return err
} else {
sessionContext.CommitTransaction(sessionContext)
}
return nil
})

if err != nil {
return nil, err
}

我已经按照 this question in Stackoverflow的指示进行了操作,也尝试了通过 this article mongodb developer进行操作

我得到的是这个错误:
(NamespaceNotFound) Cannot create namespace 
production.people in multi-document transaction.


multiple write errors: [{write errors: 
[{Cannot create namespace spura.people in multi-document transaction.}]},
{<nil>}]"

插入数据时出错,代码中有问题吗?我尝试仔细查看并尝试使用文档或文章的说明,并始终收到该错误:(

最佳答案

MongoDB 4.2和更低的does not permit creating collections in transactions。在4.4中取消了此限制。

对于4.2及更低版本,请提前create the collection

关于mongodb - mongodb无法在Go中执行事务,并且总是得到无法在多文档事务中创建 namespace ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62359271/

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