亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

mongodb ObjectId 的問題

mongodb ObjectId 的問題

Go
哈士奇WWW 2023-07-10 14:32:26
我有連接到 mongodb 數據庫的 Go 代碼。問題是,當我嘗試從集合中獲取記錄時,有一個類型的“_id”字段ObjectId,但在 mgo 驅動程序中ObjectId是type ObjectID [12]byte但是當我試圖獲得記錄時 Go 說:Reflect.Set:類型 []uint8 的值不可分配給類型 ObjectID我嘗試創建自己的[]uint8類型,但我不知道如何將[]uint8(“ObjectId”)轉換為string或通過這些 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貢獻1851條經驗 獲得超4個贊

您必須使用“預定義”bson.ObjectId來對 MongoDB 的 ObjectId 值進行建模:

type Edge struct {

? ? ID? ? ? ? ? bson.ObjectId `bson:"_id"`

? ? Name? ? ? ? string? ? ? ? `bson:"name"`

? ? StartVertex string? ? ? ? `bson:"startVertex"`

? ? EndVertex? ?string? ? ? ? `bson:"endVertex"`

}

當您通過 ID 查詢類型為 MongoDB 的 ObjectId 的對象時,請使用 type 的值bson.ObjectId。并且你可以使用以下Collection.FindId()方法:

var?id?bson.ObjectId?=?...
err?=?e.FindId(id).One(&result)


查看完整回答
反對 回復 2023-07-10
  • 1 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號