使用 go mongo-driver 运行 Find().All() 的问题

我是 mongoDB 的新手,目前我们正在尝试将我们的旧 mgo 驱动程序迁移到 go mongo-driver


在我们的旧代码中,我们使用来自全局标志 mgo 驱动程序的如下内容


//where apps is a struct

apps := []model.App{}

err = mgo.Collection.Find(query).Skip(skipCount).Limit(MaxResults).Sort("-starttime").All(&apps)


因此,对于新的 mongo-driver,我使用 Find 尝试了类似下面的方法,但是没有用。


    // Set FindOneOptions

    findOpt := options.Find()

    findOpt.SetSkip(int64(skipCount))

    limitVal := appsbody.MaxResults

    findOpt.SetLimit(int64(limitVal))

    findOpt.SetSort("-starttime")


    err = mgo.Collection.Find(query, findOpt).All(context.TODO(), &apps)

在上面的代码片段中,params 查询的类型是 map[string]interface{}。

当我尝试记录查询时,Key = type Value = dbuser两者都是字符串类型查询值最初是通过使用传递的query := url.Values{},这种情况下查询类型将是map[string][]string


我想后来它被通过了,因为map[string]interface{}不确定这是否会导致这个问题并且无法与正确的查询格式混合params,所以我什至尝试使用下面的代码转换它,但仍然没有帮助我解决问题。


    

//do a type conversion for the original query    

    q := make(map[string]interface{}, len(query))

    for key, value := range query {

        q[key] = value

    }


当我尝试运行代码时,它无法执行 Find 操作并且我得到以下错误并抛出 nil 指针


cannot transform type string to a BSON Document: WriteString can only write while positioned on a Element or Value but is positioned on a TopLevel

panic: runtime error: invalid memory address or nil pointer dereference

        panic: runtime error: invalid memory address or nil pointer dereference

        panic: runtime error: invalid memory address or nil pointer dereference

[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x564171020634]


goroutine 1 [running]:

go.mongodb.org/mongo-driver/mongo.(*Cursor).closeImplicitSession(0x5641708ab4e0?)

        go.mongodb.org/mongo-driver@v1.10.3/mongo/cursor.go:309 +0x14

panic({0x5641716c9440, 0x56417200c2d0})

        runtime/panic.go:884 +0x212

go.mongodb.org/mongo-driver/mongo.(*Cursor).Close(0xa1?, {0x5641718f9c30?, 0xc00003a078?})

        go.mongodb.org/mongo-driver@v1.10.3/mongo/cursor.go:222 +0x5f

panic({0x5641716c9440, 0x56417200c2d0})

        runtime/panic.go:884 +0x212

不确定我在这里犯了什么错误,谁能帮我解决这个问题?


繁华开满天机
浏览 89回答 1
1回答

慕工程0101907

问题在于排序值。它必须是一个文档,而不是一个简单的string. 它可以是一个映射,一个bson.M(它也是一个映射)或一个bson.D值(或任何其他“很好地”编组到 BSON 中的值,例如结构)。如果您只使用单个字段进行排序,最简单的是一个bson.M. 另请注意,可以链接对选项的方法调用(它们返回接收者):findOpt := options.Find().    SetSkip(int64(skipCount)).    SetLimit(int64(appsbody.MaxResults)).    SetSort(bson.M{"starttime": -1})如果您有多个排序键,顺序很重要,在这种情况下使用bson.D文档(地图是无序的,bson.D是键值对的有序列表):findOpt := options.Find().    SetSkip(int64(skipCount)).    SetLimit(int64(appsbody.MaxResults)).    SetSort(bson.D{{Key:"starttime", Value: -1}, {Key:"other", Value: 1}})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go