mongodb can't do transaction in Go and always got Cannot create namespace in multi-document transaction

三世轮回 提交于 2021-01-29 17:11:42

问题


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
    }

I have follow the instructions of this question in Stackoverflow and I have tried also ways from this article mongodb developer

what I got is this error:

(NamespaceNotFound) Cannot create namespace 
production.people in multi-document transaction.

and

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 :(


回答1:


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

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



来源:https://stackoverflow.com/questions/62359271/mongodb-cant-do-transaction-in-go-and-always-got-cannot-create-namespace-in-mul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!