【问题标题】:Revel+mgo golang - How to define a struct type to handle nested objects coming from the db?Revel+mgo golang - 如何定义一个结构类型来处理来自数据库的嵌套对象?
【发布时间】:2016-12-10 04:46:32
【问题描述】:

我的 mongo 收藏中有这类文档 -

{
    "_id" : "3wPEpWwECbrTrnSbh",
    "brandId" : 45,
    "title" : "brandtitle",
    "logoImg" : "brandtitle.png",
    "category" : {
        "category 1" : [ 
            {
                "cat" : "A1 Plus Champ"
            }, 
            {
                "cat" : "A108"
            }, 
            {
                "cat" : "A6"
            },            
        ],
        "category 2" : [ 
            {
                "cat" : "something"
            }, 
            {
                "cat" : "soemthing else"
            }, 
            {
                "cat" : "something else"
            },            
        ],
    },
    "isActive" : true,
    "isOnboarded" : false,
    "serviceNumber" : 18605001492.0
}

所以有几个品牌。 我可以得到所有东西,除了这个中的类别。

我的模型代码数据类型是 -

type Brand struct {
    Id string           `bson:"_id" json:"_id"`
    Brandid int         `bson:"brandId" json:"brandId"`
    Title string        `json:"title"`
    Logoimg string      `bson:"logoImg" json:"logoImg"`
    Category []string   `bson:"category" json:"category"`
    Isactive bool       `bson:"isActive" json:"isActive"`
    Isonboarded bool    `bson:"isOnboarded" json:"isOnboarded"`
    Servicenumber int   `bson:"serviceNumber" json:"serviceNumber"`
}

我现在把 Category 当作一个字符串数组,但这当然是错误的。

输出看起来像这样 -

  {
    "_id": "3wPEpWwECbrTrnSbh",
    "brandId": 45,
    "title": "brandtitle",
    "logoImg": "brandtitle.png",
    "category": null,
    "isActive": true,
    "isOnboarded": false,
    "serviceNumber": 18605001492
  }

我应该如何构造这个结构来显示我从数据库中获取的数据类型?

【问题讨论】:

    标签: mongodb go struct mgo revel


    【解决方案1】:
    type Brand struct {
        Id string           `bson:"_id" json:"_id"`
        Brandid int         `bson:"brandId" json:"brandId"`
        Title string        `json:"title"`
        Logoimg string      `bson:"logoImg" json:"logoImg"`
        Category      map[string][]map[string]string   `bson:"category" json:"category"`
        Isactive bool       `bson:"isActive" json:"isActive"`
        Isonboarded bool    `bson:"isOnboarded" json:"isOnboarded"`
        Servicenumber int   `bson:"serviceNumber" json:"serviceNumber"`
    }
    

    【讨论】:

    • 你能解释一下 [string] 的含义是什么吗?
    • @GauravOjha 抱歉,但我不确定是否可以在没有任何其他编程语言背景的情况下用纯 Go 来解释这一点。简而言之,您尝试使用更复杂的类型填充[]string 类型字段,这就是您得到nil 的原因。要在 Go 中使用嵌套 JSON(而不仅仅是),您应该了解有关 map 的更多信息。
    • 再次感谢@roman-r 提供的信息,我正在学习 Go,非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2020-08-02
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    相关资源
    最近更新 更多