首頁  >  文章  >  後端開發  >  重複使用模型並從 Fiber/MongoDB 的回應中刪除字段

重複使用模型並從 Fiber/MongoDB 的回應中刪除字段

WBOY
WBOY轉載
2024-02-08 21:27:181114瀏覽

重用模型并从 Fiber/MongoDB 的响应中删除字段

php小編子墨在這篇文章中將介紹如何在Fiber/MongoDB的回應中刪除欄位並重複使用模型。當我們從資料庫中獲取資料時,有時我們需要刪除一些字段,以滿足特定的需求或保護敏感資訊。 Fiber/MongoDB是一個流行的PHP框架,使用它可以快速建立高效能的網路應用程式。在本文中,我們將學習如何透過使用Fiber/MongoDB的強大功能來刪除字段,並在應用程式中重複使用模型,以提高程式碼的可重複使用性和可維護性。

問題內容

我試圖不建立程式碼牆,並且在不需要時不重新宣告程式碼。

我現在的兩個主要問題是:

在第47 行中,對現有使用者模型userCollection.FindOne(ctx, filter, opts).Decode(&user) 進行了覆蓋/解碼,但它沒有被更新,第46 行中的選項不被套用,除非我宣告var user2 = models.User,並在第47 行解碼為user2,然後在第49 行回傳user2

第46行有opts := options.FindOne().SetProjection(bson.M{"password": 0})。如果我使用上面範例中的第二個使用者 user2,它會在 JSON 回應中傳回密碼,但它為空。是否可以從回應中完全刪除密碼密鑰,而不創建另一個用戶模型只是為了在回應中使用它?

func CreateUser(c *fiber.Ctx) error {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    var user models.User
 
    //validate the request body
    if err := c.BodyParser(&user); err != nil {
        return c.Status(http.StatusBadRequest).JSON(responses.UserResponse{Status: http.StatusBadRequest, Message: "error", Data: &fiber.Map{"data": err.Error()}})
    }
 
    //use the validator library to validate required fields
    if validationErr := validate.Struct(&user); validationErr != nil {
        return c.Status(http.StatusBadRequest).JSON(responses.UserResponse{Status: http.StatusBadRequest, Message: "error", Data: &fiber.Map{"data": validationErr.Error()}})
    }
    var email = &user.Email
 
    count, err := userCollection.CountDocuments(ctx, bson.M{"email": email})
    if err != nil {
        return c.Status(http.StatusBadRequest).JSON(responses.UserResponse{Status: http.StatusBadRequest, Message: "error", Data: &fiber.Map{"data": "Something went wrong"}})
    }
    if count > 0 {
        return c.Status(http.StatusBadRequest).JSON(responses.UserResponse{Status: http.StatusBadRequest, Message: "error", Data: &fiber.Map{"data": "Email already in use"}})
    }
 
    //set the status, hash password, set activate token and updated at
    status := 0
    password := hashPassword(*user.Password)
    activateToken := uuid.New().String()
    updatedAt, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
 
    //create user object
    user.ID = primitive.NewObjectID()
    user.Password = &password
    user.Status = &status
    user.ResetToken = &activateToken
    user.CreatedAt = updatedAt
    user.UpdatedAt = updatedAt
 
    result, err := userCollection.InsertOne(ctx, user)
    if err != nil {
        return c.Status(http.StatusInternalServerError).JSON(responses.UserResponse{Status: http.StatusInternalServerError, Message: "error", Data: &fiber.Map{"data": err.Error()}})
    }
 
    //get created user from the DB and cast it into UserResponse model
    filter := bson.M{"_id": result.InsertedID}
    opts := options.FindOne().SetProjection(bson.M{"password": 0})
    userCollection.FindOne(ctx, filter, opts).Decode(&user)
    //return created user
    return c.Status(http.StatusOK).JSON(responses.UserResponse{Status: http.StatusOK, Message: "success", Data: &fiber.Map{"data": user}})
}

我已經嘗試建立一個不帶密碼欄位的單獨模型 UserResponse 並在 CreateUser 函數中聲明第二個使用者模型,以便能夠透過回應中的選項查看 FindOne 的輸出。

解決方法

經過幾個小時的弄清楚並將其發佈到此處後,我得到了一個輝煌的時刻。

此處所做的所有變更是將使用者重新宣告為空白使用者模型:

    user = models.User{} // <- the fix
    filter := bson.M{"_id": result.InsertedID}
    opts := options.FindOne().SetProjection(bson.M{"password": 0})
    userCollection.FindOne(ctx, filter, opts).Decode(&user)

以上是重複使用模型並從 Fiber/MongoDB 的回應中刪除字段的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除