I use the following packages:
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
I try to handle a nested struct and put this into mongodb. The following code does the job correctly, but I don't know if this is the right way.
// init
type DummyStruct struct {
User string `bson:"user"`
Foo FooType `bson:"foo"`
}
type FooType struct {
BarA int `bson:"bar_a"`
BarB int `bson:"bar_b"`
}
// main
foobar := DummyStruct{
User: "Foobar",
Foo: FooType{
BarA: 123,
BarB: 456,
},
}
// Insert
if err := c.Insert(foobar); err != nil {
panic(err)
}
Is it neccessary to build the nested struct in 2 parts?
If I use a json->golang struct converter (https://mholt.github.io/json-to-go/)
I'll get the following struct
type DummyStructA struct {
User string `bson:"user"`
Foo struct {
BarA int `bson:"bar_a"`
BarB int `bson:"bar_b"`
} `bson:"foo"`
}
Now I don't know how I could fill this struct.
I tried this:
foobar := DummyStructA{
User: "Foobar",
Foo: {
BarA: 123,
BarB: 456,
},
}
but got this error: missing type in composite literal
I Also tried this
foobar := DummyStructA{
User: "Foobar",
Foo{
BarA: 123,
BarB: 456,
},
}
and got this 2 errors:
mixture of field:value and value initializers
undefined: Foo
Or is it necessary to handle the struct (DummyStructA) with bson.M?