我是 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
不确定我在这里犯了什么错误,谁能帮我解决这个问题?
慕工程0101907
相关分类