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
Answers
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
You can define a registry for your collection (or database) using mgocompat package.