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

PHPz
Release: 2024-02-06 10:48:11
forward
849 people have browsed it

用户 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)
Copy after login

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"}})
}
Copy after login

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})
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!