dongtiao5094 2018-01-19 06:56
浏览 48
已采纳

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?

  • 写回答

2条回答 默认 最新

  • dqq46733 2018-01-19 09:34
    关注

    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
    ",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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 YOLOv8obb获取边框坐标时报错AttributeError: 'NoneType' object has no attribute 'xywhr'
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸