3 回答

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()

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
- 3 回答
- 0 關(guān)注
- 639 瀏覽
添加回答
舉報