关于 go: mongodb ObjectId 的问题
Troubles with mongodb ObjectId
我有连接到 mongodb 数据库的 Go 代码。
问题是当我试图从集合中获取记录时,有一个 ObjectId 类型的"_id"字段,但在 mgo 驱动程序 ObjectId 中是
|
1
|
type ObjectID [12]byte
|
但是当我试图获得记录时,Go 说:
reflect.Set: value of type []uint8 is not assignable to type ObjectID
我尝试创建自己的 []uint8 类型,但我不知道如何将 []uint8 ("ObjectId") 转换为 string 或通过这些 id 查找一些记录。
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// ObjectId type that mongodb wants to see
type ObjectID []uint8 // model
// method for getting record by those id //edges collection var result models.Edge err = e.Find(bson.M{"_id": fmt.Sprintln("ObjectId('", id,"')")}).One(&result) |
您必须使用"预定义"bson.ObjectId 来对 MongoDB 的 ObjectId 的值进行建模:
|
1
2 3 4 5 6 |
type Edge struct {
ID bson.ObjectId `bson:"_id"` Name string `bson:"name"` StartVertex string `bson:"startVertex"` EndVertex string `bson:"endVertex"` } |
当您通过 ID 查询类型为 MongoDB 的 ObjectId 的对象时,请使用类型为 bson.ObjectId 的值。您可以使用 Collection.FindId() 方法:
|
1
2 |
var id bson.ObjectId = ...
err = e.FindId(id).One(&result) |
在此处查看详细信息:使用 mgo 按 id 查找;和 MongoDB 切片查询到 golang