1

i am stuck in a issue where i am trying to fetch the user details by doing

err := userCollection.FindOne(ctx, bson.M{"email": input.Email}).Decode(&input)

in my user controller but it is returning nil. I have places a mongo.ErrNoDocuments check but its still passing to nil check and returning nothing , but i have a user with 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"}})
}

Any help is appreciated . Thanks in advance

Biswas Sampad
  • 413
  • 1
  • 6
  • 19
  • What is your issue? You say you don't get any errors and still not getting any documents? You compare `err` to `nil`, you should use inequality: `err != nil`. Also you don't send back `input` to the user, why would the result contain anything? – icza Dec 15 '22 at 13:29
  • That i was testing if it is going to nil , and it is going to nil . – Biswas Sampad Dec 15 '22 at 13:32
  • OK, so `err` _is_ `nil`, but still, you decode the document into `input`, but you don't send `input` in the response. Why would the client see the value of `input` then? – icza Dec 15 '22 at 13:36
  • Then whats the best way to get the user data in given conditions, I am new to go actually – Biswas Sampad Dec 15 '22 at 14:09

1 Answers1

1

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

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