我有連接到 mongodb 數(shù)據(jù)庫(kù)的 Go 代碼。問(wèn)題是,當(dāng)我嘗試從集合中獲取記錄時(shí),有一個(gè)類型的“_id”字段ObjectId,但在 mgo 驅(qū)動(dòng)程序中ObjectId是type ObjectID [12]byte但是當(dāng)我試圖獲得記錄時(shí) Go 說(shuō):Reflect.Set:類型 []uint8 的值不可分配給類型 ObjectID我嘗試創(chuàng)建自己的[]uint8類型,但我不知道如何將[]uint8(“ObjectId”)轉(zhuǎn)換為string或通過(guò)這些 id 查找某些記錄。// ObjectId type that mongodb wants to seetype ObjectID []uint8// modeltype Edge struct { ID ObjectID `bson:"_id"` Name string `bson:"name"` StartVertex string `bson:"startVertex"` EndVertex string `bson:"endVertex"`}// method for getting record by those idsession, err := mgo.Dial(config.DatabaseURL) if err != nil { fmt.Printf("Error is: %s", err) } defer session.Close() session.SetMode(mgo.Monotonic, true) //edges collection e := session.DB(config.DatabaseName).C(config.EdgesCollection) var result models.Edge err = e.Find(bson.M{"_id": fmt.Sprintln("ObjectId('", id, "')")}).One(&result) if err != nil { fmt.Println("Error is: ", err) }
1 回答

繁花不似錦
TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超4個(gè)贊
您必須使用“預(yù)定義”bson.ObjectId
來(lái)對(duì) MongoDB 的 ObjectId 值進(jìn)行建模:
type Edge struct {
? ? ID? ? ? ? ? bson.ObjectId `bson:"_id"`
? ? Name? ? ? ? string? ? ? ? `bson:"name"`
? ? StartVertex string? ? ? ? `bson:"startVertex"`
? ? EndVertex? ?string? ? ? ? `bson:"endVertex"`
}
當(dāng)您通過(guò) ID 查詢類型為 MongoDB 的 ObjectId 的對(duì)象時(shí),請(qǐng)使用 type 的值bson.ObjectId
。并且你可以使用以下Collection.FindId()
方法:
var?id?bson.ObjectId?=?... err?=?e.FindId(id).One(&result)
- 1 回答
- 0 關(guān)注
- 126 瀏覽
添加回答
舉報(bào)
0/150
提交
取消