bson  json 


,最好的情况下,也许你可以使用:

 类型投资结构{
基础
符号字符串` json:symbolbinding:required
组字符串`json:group,omitemptybson:,omitempty`
字段bson.M`json:fields`

 * Group 

I'm somewhat new to typed languages like Go and am trying to learn the best ways to implement things.

I have two structs that represent models that will be inserted into a mongodb database. One struct (Investment) has the other struct (Group) as one of its fields.

type Group struct {
    Base
    Name string `json:"name" bson"name"`
}

type Investment struct {
    Base
    Symbol string `json:"symbol" bson:"symbol" binding:"required"`
    Group  Group  `json:"group" bson:"group"`
    Fields bson.M `json:"fields" bson:"fields"`
}

The problem I'm having is that in the Investment model, Group is not required. If there is no group, I think its better for it to not be inserted in the db. Whats the best way to handle a db model such as this in Go?

,omitempty
jsonbson,omitempty,omitempty
*GroupInvestment""
bsonjson

So, best case, maybe you can just use:

type Investment struct {
    Base
    Symbol string `json:"symbol" binding:"required"`
    Group string  `json:"group,omitempty" bson:",omitempty"`
    Fields bson.M `json:"fields"`
}
*Group

这篇关于在golang中为空或不需要结构字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!