英文:
dsnap.Data() returns nil if the document does not exist
问题
我已经编写了一个名为GetUser的控制器,用于根据查询中提供的id从数据库(Firestore)中获取特定用户。如果数据库中不存在该用户,则应返回消息“用户未找到”。但是,除了这条消息之外,我还收到了响应中的nil关键字。
我收到的响应如下:
{
"message": "用户未找到"
}null
当我悬停在dsnap.Data()上时,我得到的信息是:
(firestore.DocumentSnapshot).Data on pkg.go.dev
Data将DocumentSnapshot的字段作为映射返回。它等效于
var m map[string]interface{}
d.DataTo(&m)
除非文档不存在,否则它返回nil。
控制器代码如下:
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": "用户未找到",
})
}
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吗?
谢谢。
英文:
I have written a controller GetUser to get a particular user from Database(Firestore) on the basis of id I put in the query. If the user is not present in the database then it should give the message that "User not found". But along with this message I am getting nil keyword also in response.
The response I am getting:
{
"message": "User not found"
}null
When I hover on dsnap.Data() I get the information that
(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.
Controller:
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 reference link: https://pkg.go.dev/cloud.google.com/go/firestore@v1.6.1#DocumentSnapshot.Data
Can you guys please tell me how can I remove nil from the response?
Thank you.
答案1
得分: 0
这个问题已经解决了。我在“用户未找到”响应后面写了"return"。
英文:
This problem is solved now. I write "return" after the User not found response.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论