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