3 回答
TA贡献1853条经验 获得超6个赞
错误消息告诉mongoDoc["_id"]is of type interface{},它的值是 type primitive.ObjectID。这不是 a string,它是一个独特的类型。您只能primitive.ObjectID从接口值中键入 assert。
如果你想要string这个 MongoDB ObjectId 的表示,你可以使用它的ObjectID.Hex()方法来获取 ObjectId 字节的十六进制表示:
mongoId := mongoDoc["_id"]
stringObjectID := mongoId.(primitive.ObjectID).Hex()
TA贡献1772条经验 获得超6个赞
2021 年情况发生了变化。这里有一个更简单的方法。它让用户从模型中询问它来自界面的类型,然后一切都很好
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 关注
- 743 浏览
添加回答
举报
