mongodb 无法在 Go 中进行事务并且总是得到无法在多文档事务中创建命名空间 [英] mongodb can't do transaction in Go and always got Cannot create namespace in multi-document transaction

查看:124
本文介绍了mongodb 无法在 Go 中进行事务并且总是得到无法在多文档事务中创建命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过包装事务来创建一个插入一个数据的函数,并且我已经在 mongodb 中设置了副本,我在本地和 MongoDB 地图集中尝试过,错误是一样的,这是代码:

I am trying to create a function that InsertOne data by wrap transaction, and I already to replica set in mongodb also, I tried in local and and MongoDB atlas the error were same, here is the code:

    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
    }

我已按照Stackoverflow中的这个问题的说明进行操作,并且我也尝试了本文 mongodb 开发者

I have follow the instructions of this question in Stackoverflow and I have tried also ways from 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>}]"

插入数据时出错,是我的代码有问题吗?我试过仔细查看并尝试文档或文章的说明,但总是得到那个错误:(

it got error when I inserted data , is that something wrong in my code? I have tried look carefully and try the instruction of document or articles and always got that error :(

推荐答案

MongoDB 4.2 及更低版本 不允许在交易中创建集合.此限制在 4.4 中解除.

MongoDB 4.2 and lower does not permit creating collections in transactions. This restriction is lifted in 4.4.

对于 4.2 及更低版本,创建集合时间.

For 4.2 and lower, create the collection ahead of time.

这篇关于mongodb 无法在 Go 中进行事务并且总是得到无法在多文档事务中创建命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆