登录
首页 >  Golang >  Go问答

golang mongo-db 事务无法创建命名空间

来源:stackoverflow

时间:2024-04-30 16:27:37 419浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《golang mongo-db 事务无法创建命名空间》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我正在尝试在 golang 中使用 mongo-db 进行数据库事务,但出现无法创建名称空间错误

// for a replica set, include the replica set name and a seedlist of the members in the uri string; e.g.
    // uri := "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaset=myrepl"
    // for a sharded cluster, connect to the mongos instances; e.g.
    // uri := "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/"
    uri := "mongodb://mongo-0/block-recorder?replicaset=rs0"
    // var uri string

    clientopts := options.client().applyuri(uri)
    client, err := mongo.connect(ctx, clientopts)
    if err != nil {
        panic(err)
    }
    defer func() { _ = client.disconnect(ctx) }()

    // prereq: create collections.
    wcmajority := writeconcern.new(writeconcern.wmajority(), writeconcern.wtimeout(1*time.second))
    wcmajoritycollectionopts := options.collection().setwriteconcern(wcmajority)
    blockcollection := client.database("block-recorder").collection("block", wcmajoritycollectionopts)

    // step 1: define the callback that specifies the sequence of operations to perform inside the transaction.
    callback := func(sessctx mongo.sessioncontext) (interface{}, error) {
        // important: you must pass sessctx as the context parameter to the operations for them to be executed in the
        // transaction.
        dbblock := model.transferblockdata(block)
        if _, err := blockcollection.insertone(sessctx, dbblock); err != nil {
            return nil, err
        }
        return nil, nil
    }

    // step 2: start a session and run the callback using withtransaction.
    session, err := client.startsession()
    if err != nil {
        panic(err)
    }
    defer session.endsession(ctx)

    result, err := session.withtransaction(ctx, callback)
    if err != nil {
        panic(err)
    }
    fmt.printf("result: %v\n", result)

这是我正在使用的示例代码,出现以下错误

panic: multiple write errors: [{write errors: [{Cannot create namespace block-recorder.Block in multi-document transaction.}]}, {<nil>}]

我大多数时候都使用 gorm,这是我第一次在 golang 中使用 mongo,它说首先创建集合,我已经在这样做了?还有其他方法可以在 golang 中为 mongo 创建集合吗? 如何使用结构数据示例进行正确的交易?


解决方案


MongoDB 服务器当前无法在事务中创建集合。

如果您的应用程序将数据插入到不存在的集合中,则在大多数情况下服务器会透明地创建该集合。但如果交易处于活动状态,则目前此功能不起作用。

提前创建集合,以便它在事务执行时存在。

在应用程序中实例化集合对象实际上并不创建集合。要创建集合,请尝试 go 驱动程序中相当于 createCollection 的内容。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>