登录
首页 >  Golang >  Go问答

Go Fiber Go Mongo 数据存在,用户 findOne 返回 nil

来源:stackoverflow

时间:2024-02-15 23:36:19 322浏览 收藏

哈喽!今天心血来潮给大家带来了《Go Fiber Go Mongo 数据存在,用户 findOne 返回 nil》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

我遇到了一个问题,我试图通过执行以下操作来获取用户详细信息

err := usercollection.findone(ctx, bson.m{"email": input.email}).decode(&input)

在我的用户控制器中,但它返回零。我有一个 mongo.errnodocuments 检查,但它仍然传递到 nil 检查并且不返回任何内容,但我有一个具有相同电子邮件 id 的用户。我的 usercontroller 看起来像这样。

func SignInUser(c *fiber.Ctx) error {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    var input models.User
    defer cancel()

    if err := c.BodyParser(&input); err != nil {
        return c.Status(http.StatusBadRequest).JSON(responses.UserResponse{Status: http.StatusBadRequest, Message: "error", Data: &fiber.Map{"data": err.Error()}})
    }

    input.Email = util.NormalizeEmail(input.Email)
    fmt.Println("received data", input.Email)
    err := userCollection.FindOne(ctx, bson.M{"email": input.Email}).Decode(&input)

    if err == mongo.ErrNoDocuments {
        fmt.Println("User not found>>>")
    } else if err == nil {
        fmt.Println("err")
    }
    return c.Status(http.StatusNotFound).JSON(responses.UserResponse{
        Status:  http.StatusNotFound,
        Message: "Account not found",
        Data: &fiber.Map{
            "data": "No Account belongs to given credentials"}})
}

感谢任何帮助。提前致谢


正确答案


您应该在函数末尾返回您的用户模型:

return c.JSON(fiber.Map{"status": "success", "message": "User found", "data": input})

终于介绍完啦!小伙伴们,这篇关于《Go Fiber Go Mongo 数据存在,用户 findOne 返回 nil》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>