Skip to content

Proper way for handling null value (nil) #48

Answered by mehran-prs
SebUndefined asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @SebUndefined
Just use pointers:

// User contains user information
type User struct {
	mgm.DefaultModel `bson:",inline"`
	Name             *string `json:"name"`
	Age              *int   `bson:"age"`
}

And if you want to omit empty values in your DB (by default nil values will be as null value on DB), you can use omitempty tag on your field.
e.g.,

// User contains user information
type User struct {
	mgm.DefaultModel `bson:",inline"`
	Name             *string `json:"name,omitempty"`
	Age              *int    `bson:"age,omitempty"`
}

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by mehran-prs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants