使用 golang、gin 和 gorm 与 postgres (如电子邮件)

http://img4.mukewang.com/63563ce80001139b15860520.jpg

我有这样的事情,我想检查数据库中是否已经存在电子邮件:


func RegisterUser(c *gin) {

var user models.User

if err := c.ShouldBindJSON(&user); err != nil {

    c.JSON(http.StatusBadRequest, gin.H{

        "messAge": err.Error(),

        "data":    "",

    })

    return

}

// **I TRIED SOEMTHING LIKE THIS**

err := database.DB.Find(&user.Email).Error

if err != nil {

    c.JSON(401, gin.H{"MESSAGE": "Email ALREADY exist",

    return

}

// **but is not working, because ANY mail it give me error**



if !strings.Contains(user.Email, "@") {

    c.JSON(400, gin.H{"MESSAGE": utils.ErrEmailWrong})

    return

}


if len(user.Password) < 4 {

    c.JSON(400, gin.H{"MESSAGE": utils.ErrPasswordLength})

    return

}


database.DB.Create(&user)

c.JSON(200, gin.H{

    "MESSAGE": "CREATED",

})

}

使用此代码,每次都告诉我:电子邮件已存在,仅第一次有效。


慕森王
浏览 144回答 4
4回答

Qyouu

请阅读文档:&nbsp;https ://gorm.io/docs/query.htmlvar&nbsp;userFind&nbsp;models.User database.DB.Where("email&nbsp;=&nbsp;?",&nbsp;user.Email).First(&userFind)

海绵宝宝撒

因为,您的 struct 对象不是切片。你应该使用ErrRecordNotFound.注意:ErrRecordNotFound仅适用于First, Last,Take预计会返回一些结果。并RecordNotFound在 V2 中删除。if err != nil {&nbsp; &nbsp; &nbsp;if errors.Is(err, gorm.ErrRecordNotFound){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;c.JSON(401, gin.H{"MESSAGE": "Email Not Found",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; c.JSON(401, gin.H{"MESSAGE": "Your Message",&nbsp; &nbsp; return}或者如果你想避免这个错误ErrRecordNotFound,你可以使用Findlike方法接受结构和切片数据。并像这样检查:db.Limit(1).Find(&user),Findresult.RowsAffected // returns count of records found为了更好地理解,请参阅此处的链接:https ://gorm.io/docs/v2_release_note.html#ErrRecordNotFound和https://gorm.io/docs/query.html而且,如果您想通过电子邮件在数据库中添加记录,那么您应该删除唯一约束并在创建记录时检查错误。如果成功创建记录,则返回成功响应,否则返回相应的错误消息。

芜湖不芜

它终于工作了!谢谢大家回答!

慕容708150

您应该在绑定之后和数据库查询之前验证输入将您的电子邮件列更改为唯一尝试将经过验证的数据插入到 db如果成功 => 200(没有类似的电子邮件)if err => 检查错误码例如:func IsUniqueContraintViolation(err error) bool {&nbsp; &nbsp; &nbsp; &nbsp; if pgError, ok := err.(*pgconn.PgError); ok && errors.Is(err, pgError) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if pgError.Code == "23505" {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; }有关更多信息,您应该查看GoDoc pg lib和可能的错误代码,然后您可以返回合适的错误代码顺便提一句。希望您不要将清晰的密码保存到数据库:D
打开App,查看更多内容
随时随地看视频慕课网APP