Search code examples
mongodbgobson

Golang Mongo DB Embedded Fields with Inline Tag missing


I have a struct that is using json and bson tags:

type PlayerGameStats struct {
    Hitting struct {
        Overall  hittingStats `json:"overall,omitempty" bson:"overall,omitempty"`
        SeasonTd struct {
            OBP          float64       `json:"obp,omitempty" bson:"obp,omitempty"`
            OPS          float64       `json:"ops,omitempty" bson:"ops,omitempty"`
            SLG          float64       `json:"slg,omitempty" bson:"slg,omitempty"`
            hittingStats `bson:",inline"`
        } `json:"seasontd,omitempty" bson:"season_td,omitempty"`
    } `json:"hitting,omitempty" bson:"hitting,omitempty"`
}


type hittingStats struct {
    AB     int `json:"ab,omitempty" bson:"ab,omitempty"`
    RBI    int `json:"rbi,omitempty" bson:"rbi,omitempty"`
    AP     int `json:"ap,omitempty" bson:"ap,omitempty"`
    Onbase struct {
        S  int `json:"s,omitempty" bson:"s,omitempty"`
        D  int `json:"d,omitempty" bson:"d,omitempty"`
        T  int `json:"t,omitempty" bson:"t,omitempty"`
        HR int `json:"hr,omitempty" bson:"hr,omitempty"`
        TB int `json:"tb,omitempty" bson:"tb,omitempty"`
        BB int `json:"bb,omitempty" bson:"bb,omitempty"`
        H  int `json:"h,omitempty" bson:"h,omitempty"`
    } `json:"onbase,omitempty" bson:"onbase,omitempty"`
}

When I unmarshal the received response I get the proper values in the embedded hittingStats fields but when I upsert the PlayerGameStats to my collection the embedded fields are missing. PlayerGameStats is included in another higher level struct but I don't think that is the issue.

From what I understand about the inline tag it should "If the field type is a struct or map field, the field will be flattened when marshalling and unflattened when unmarshalling." and from other stack overflow posts this seems like it should work?

All help is appreciated!!

I tried not embedding the fields and using the inline tag but this obviously breaks the json form I need to Unmarshal.


Solution

  • I actually continued to debug and of course figured out the issue right after finally posting the question. hittingStats needs to be exported (HittingStats)! Simple fix and is now working as expected :)

    Not sure if I should leave this here or delete it?