【问题标题】:dsnap.Data() returns nil if the document does not exist如果文档不存在,dsnap.Data() 返回 nil
【发布时间】:2022-01-05 11:36:35
【问题描述】:

我已经编写了一个控制器GetUser,以在id 的基础上从数据库(Firestore)中获取特定用户,我输入了查询。如果用户不在数据库中,那么它应该给出"User not found" 的消息。但随着这条消息的出现,我也收到了nil 关键字作为回应。

我得到的回应:

{
    "message": "User not found"
}null

当我将鼠标悬停在dsnap.Data() 上时,我得到的信息是

(firestore.DocumentSnapshot).Data on pkg.go.dev

Data returns the DocumentSnapshot's fields as a map. It is equivalent to

var m map[string]interface{}
d.DataTo(&m)
except that it returns nil if the document does not exist.

控制器:

func GetUser(c *gin.Context) {
    paramID := c.Params.ByName("id")
    ........
    ........
    ........
    dsnap, err := client.Collection("users").Doc(paramID).Get(ctx)
    if err != nil {
        fmt.Print(err)
        c.IndentedJSON(http.StatusNotFound, gin.H{
            "message": "User not found",
        })
    }
    m := dsnap.Data()
    c.IndentedJSON(http.StatusNotFound, gin.H(m))

}

Firestore 参考链接:https://pkg.go.dev/cloud.google.com/go/firestore@v1.6.1#DocumentSnapshot.Data

你们能告诉我如何从回复中删除nil 吗? 谢谢。

【问题讨论】:

  • 写入用户未找到响应后从函数返回。
  • @CeriseLimón Limón 非常感谢。它对我有用。问题解决了。但是你能告诉我写完 return 之后到底发生了什么吗?
  • 将用户未找到消息写入响应后,该函数继续将 dsnap.Data() 的 JSON 编码写入响应。在未找到用户的情况下,将 nil 返回值编码为 null 并写入响应。 return 语句导致函数在将 dsnap.Data() 的 JSON 编码写入响应之前返回。

标签: api go google-cloud-firestore go-gin


【解决方案1】:

这个问题现在解决了。我在User not found 响应之后写"return"

【讨论】:

    猜你喜欢
    • 2014-09-29
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2017-05-19
    • 1970-01-01
    相关资源
    最近更新 更多