因此,将模型插入MongoDB时,我遇到了一些意外的行为。当我通过Postman发送一个空白到我的服务器并将其插入数据库时,返回的结果是postman name
number 默认值为他们的预期默认值, 0
和“”
,但是对于数据
,而不是默认为空数组,它默认为 null
,即使尽管在Go Console插入之前和之后,其价值并非零,而是一个空数组。分配 data
字段一个空 [] int {}
在插入解决问题之前,手动将空数组作为Postman的数据字段发送,但我很好奇如果有其他方法可以保证数组字段默认为 []
而不是 null
插入时。
这是我的模型:
type Test struct{
Name string `json:"name" bson:"name"`
Number int `json:"number" bson:"number"`
Data []int `json:"data" bson:"data"`
}
So I have ran into some unexpected behavior when inserting a model into mongoDB. When I send an empty body via Postman to my server and insert it into my database, the returned result to Postman had name
and number
default to their expected default values, 0
and ""
, but for data
, instead of defaulting to an empty array, it defaulted to null
instead, even though its value printed out before and after insertion in the Go console isn't nil, but an empty array. Assigning the data
field an empty []int{}
before insertion solves the issue, and so does manually sending an empty array as the data field from Postman, but I was curious if there was any other way to guarantee that array fields default to []
and not null
when getting inserted.
Here is my model:
type Test struct{
Name string `json:"name" bson:"name"`
Number int `json:"number" bson:"number"`
Data []int `json:"data" bson:"data"`
}
发布评论
评论(2)
当您保存值演示Go Playground链接 :
also, you can check this link:
demo go playground link: https://go.dev/play/p/1WlO_44hnco
also, you can check this link: Autofill created_at and updated_at in golang struct while pushing into mongodb
您可以使用MGOCOMPAT软件包为您的集合(或数据库)定义注册表。
You can define a registry for your collection (or database) using mgocompat package.