Search code examples
mongodbgomongo-go

MongoDB Go Driver unable to unmarshal nested documents correctly


I've a setter and getter that operates on a specific field in a collection. The setter works fine and the documents are updated as expected, however the getter does not return populated structs correctly. What am I doing wrong ?


Collection as a Go struct:


type Model struct {
    ID         primitive.ObjectID `bson:"_id,omitempty"`
    EntityType string             `bson:"entity_type,omitempty"`
    EntityID   string             `bson:"entity_id,omitempty"`
    ConfigSource ConfigSources `bson:"config_source,inline,omitempty"`
}

type ConfigSources struct {
    Configs []ConfigSource `bson:"configs,omitempty"`
}

type ConfigSource struct {
    Hour   int    `bson:"hour"`
    Source string `bson:"source"`
}

Setter snippet:

cfg := ConfigSources{
    Configs: []ConfigSource{
        {
            Hour: 1,
            Source: "Hour_1_Source",
        },
        {
            Hour: 2,
            Source: "Hour_2_Source",
        },
    },
}
c := db.Collection("foo")
selectorQuery := bson.M{"entity_id": entityId}
updateQuery := bson.M{"$set": bson.M{"config_source": configName}}
result, err := c.UpdateMany(ctx, selectorQuery, updateQuery)

Getter snippet:

c := db.Collection("foo")
q, err := c.Find(ctx, bson.M{"_id": bson.M{"$in": idsImQuerying}})
if err != nil {
    return nil
}
var results []Model
err = q.All(ctx, &results)
fmt.Printf("\n\n\n\n%#v\n\n\n\n", results) // this output is shown below

Obtained result:

[]Model{
    Model{
        ID:primitive.ObjectID{0x5a, 0xa9, 0x7a, 0x40, 0xdf, 0xe5, 0x90, 0x44, 0x49, 0xdb, 0x61, 0x4},
        EntityType:"CELL",
        EntityID:"4110902605985611776",
        ConfigSource:ConfigSources{
            Configs:[]ConfigSource(nil)
        }
    }
}

Field as viewed in Atlas :

screenshot of atlas document viewer


Solution

  • Once I removed inline from Model struct it is working fine

         type Model struct {
            ID         primitive.ObjectID `bson:"_id,omitempty"`
            EntityType string             `bson:"entity_type,omitempty"`
            EntityID   string             `bson:"entity_id,omitempty"`
            ConfigSource ConfigSources `bson:"config_source,omitempty"`
        }