Home  >  Article  >  Backend Development  >  User findOne returns nil but data exists in Go Fiber Go Mongo

User findOne returns nil but data exists in Go Fiber Go Mongo

PHPz
PHPzforward
2024-02-06 10:48:11836browse

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

Question content

I have a problem where I am trying to get user details by doing the following

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

in my user controller but it returns nil. I have a mongo.errnodocuments check but it still passes to nil check and returns nothing but I have a user with the same email id. My usercontroller looks like this.

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"}})
}

Thanks for any help. Thanks in advance


Correct answer


You should return your user model at the end of the function:

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

The above is the detailed content of User findOne returns nil but data exists in Go Fiber Go Mongo. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete