Search code examples
sqlgogo-gorm

Check if a user already exists in a DB


How can I check if a user already exists in the database using gorm? I cannot seem to find a proper way to do so without an error logging to the console if no user was found.

This is my code so far

result := models.User{}
err := connection.DB.First(&result, "username = ?", user.Username).Error

if err == gorm.ErrRecordNotFound {

    if err := connection.DB.Create(&user).Error; err != nil {

        return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{

            "error": "internal server error",
        })
    }

    return c.Status(fiber.StatusCreated).JSON(fiber.Map{
        "message": "user created",
    })
}

if result.Username != "" {

    return c.Status(fiber.StatusConflict).JSON(fiber.Map{
        "error": "username already exists",
    })
}

return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
    "error": "internal server error",
})

but if a new user is created, an error is printed to the terminal saying the record was not found.


Solution

  • You can also use FirstOrCreate

    From Doc:

    Get first matched record or create a new one with given conditions (only works with struct, map conditions)

    u := connection.DB.FirstOrCreate(user)
    
    if u.Error != nil {
        return c.Status(fiber.StatusInternalServerError).JSON(
            fiber.Map{
                "error": "Internal server error",
            }
        )
    }
    
    if u.RowsAffected == 1 {
        return c.Status(fiber.StatusCreated).JSON(
            fiber.Map{
                "message": "User created successfully",
            }
        )
    }
    
    return c.Status(fiber.StatusBadRequest).JSON(
        fiber.Map{
            "error": "Username already exists",
        }
    )