第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

Primitive.ObjectID 到 Golang 中的字符串

Primitive.ObjectID 到 Golang 中的字符串

Go
楊__羊羊 2022-05-23 16:35:11
我正在嘗試將類型轉(zhuǎn)換primitive.ObjectID為stringGo 中的類型。我正在使用mongo-driver來自go.mongodb.org/mongo-driver.我嘗試使用類型斷言mongoId := mongoDoc["_id"];stringObjectID := mongoId.(string)哪個 VSCode 接受。代碼被編譯,當(dāng)它到達(dá)這個特定的代碼行時,它會拋出這個錯誤panic: interface conversion: interface {} is primitive.ObjectID, not string
查看完整描述

3 回答

?
墨色風(fēng)雨

TA貢獻(xiàn)1853條經(jīng)驗 獲得超6個贊

錯誤消息告訴mongoDoc["_id"]is of type interface{},它的值是 type primitive.ObjectID。這不是 a string,它是一個獨特的類型。您只能primitive.ObjectID從接口值中鍵入 assert。


如果你想要string這個 MongoDB ObjectId 的表示,你可以使用它的ObjectID.Hex()方法來獲取 ObjectId 字節(jié)的十六進(jìn)制表示:


mongoId := mongoDoc["_id"]

stringObjectID := mongoId.(primitive.ObjectID).Hex()


查看完整回答
反對 回復(fù) 2022-05-23
?
夢里花落0921

TA貢獻(xiàn)1772條經(jīng)驗 獲得超6個贊

2021 年情況發(fā)生了變化。這里有一個更簡單的方法。它讓用戶從模型中詢問它來自界面的類型,然后一切都很好


var user models.User


query := bson.M{"$or": []bson.M{{"username": data["username"]}, {"email": data["username"]}}}


todoCollection := config.MI.DB.Collection(os.Getenv("DATABASE_COLLECTION_USER"))

todoCollection.FindOne(c.Context(), query).Decode(&user)


stringObjectID := user.ObjectID.Hex()

上面的代碼適用于這個接口:


type User struct {

    ObjectID primitive.ObjectID `bson:"_id" json:"_id"`


    // Id        string    `json:"id" bson:"id"`

    Username      string    `json:"username" gorm:"unique" bson:"username,omitempty"`

    Email         string    `json:"email" gorm:"unique" bson:"email,omitempty"`

    Password      []byte    `json:"password" bson:"password"`

    CreatedAt     time.Time `json:"createdat" bson:"createat"`

    DeactivatedAt time.Time `json:"updatedat" bson:"updatedat"`

}

因此:這 3 行代碼會做得很好:


objectidhere := primitive.NewObjectID()

stringObjectID := objectidhere.Hex()


filename_last := filename_rep + "_" + stringObjectID + "." + fileExt


查看完整回答
反對 回復(fù) 2022-05-23
?
慕碼人2483693

TA貢獻(xiàn)1860條經(jīng)驗 獲得超9個贊

現(xiàn)在你可以做 mongoId.Hex()



查看完整回答
反對 回復(fù) 2022-05-23
  • 3 回答
  • 0 關(guān)注
  • 639 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號