我使用以下包:
“gopkg.in/mgo.v2”
“gopkg.in/mgo.v2/bson”
我尝试处理嵌套结构并将其放入 mongodb。 下面的代码可以正确完成工作,但我不知道这是否是正确的方法。
// 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)
}
是否需要分两部分构建嵌套结构?
如果我使用 json->golang 结构转换器 (https://mholt.github.io/json-to-go/)
我将得到以下结构
type DummyStructA struct {
User string `bson:"user"`
Foo struct {
BarA int `bson:"bar_a"`
BarB int `bson:"bar_b"`
} `bson:"foo"`
}
现在我不知道如何填充这个结构。
我试过这个:
foobar := DummyStructA{
User: "Foobar",
Foo: {
BarA: 123,
BarB: 456,
},
}
但出现此错误:复合文字中缺少类型
我也试过了
foobar := DummyStructA{
User: "Foobar",
Foo{
BarA: 123,
BarB: 456,
},
}
并得到这 2 个错误:
field:value 和 value 初始值设定项的混合
未定义:富
或者是否有必要用 bson.M 处理结构体 (DummyStructA)?
最佳答案
你可以这样做
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))
}
输出是这样的
test data
{"user":"test","foo":{"barA":123,"bar_b":321}}
关于mongodb - mongodb中的嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48335639/