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