0
votes

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?

2

2 Answers

1
votes

You can do this like this

package main

import (
    "fmt"
    "encoding/json"
)

type DummyStruct struct {
    User     string  `bson:"user" json:"user"`
    Foo      FooType `bson:"foo" json:"foo"`
}

type FooType struct {
    BarA int `bson:"barA" json:"barA"`
    BarB int `bson:"bar_b" json:"bar_b"`
}

func main() {
    test:=DummyStruct{}
    test.User="test"
    test.Foo.BarA=123
    test.Foo.BarB=321
    b,err:=json.Marshal(test)
    if err!=nil{
        fmt.Println("error marshaling test struct",err)
        return
    }
    fmt.Println("test data\n",string(b))
}

OutPut is like this

test data
{"user":"test","foo":{"barA":123,"bar_b":321}}

Try in go play ground: https://play.golang.org/p/s32pMvqP6Y8

0
votes

If you define 2 different struct like in your question. You need to declare foobar like:

foobar := DummyStructA{
User: "Foobar",
Foo: FooType{
    BarA: 123,
    BarB: 456,
},

}

But it's not necessary to define a second type to handle this scenario. You could use an anonymous struct like:

type DummyStructA {
    User string `bson:"user"`
    Foo struct{
       Name string `bson:"name"`
       Age int `bson:"age"`
    } `bson: "foo"`
}

But it becomes cumbersome while trying to fill data in.

foobar := DummyStructA{
     User: "hello",
     Foo : struct{
           Name string
           Age int
         }{
         Name: "John",
         Age: 50,
     }
}