Search code examples
mongodbgobsonmgo

nested struct in mongodb


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?


Solution

  • 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