英文:
User findOne is returning nil but data is present in Go fiber Go Mongo
问题
我被卡在一个问题上,我试图通过以下方式获取用户详细信息:
err := userCollection.FindOne(ctx, bson.M{"email": input.Email}).Decode(&input)
但是它返回了nil。我已经添加了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"}})
}
非常感谢您的帮助。提前致谢。
英文:
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
答案1
得分: 1
你应该在函数的末尾返回你的用户模型:
return c.JSON(fiber.Map{"status": "success", "message": "找到用户", "data": input})
英文:
You should return your user model at the end of the function:
return c.JSON(fiber.Map{"status": "success", "message": "User found", "data": input})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论