Search code examples
mongodbgostructmgorevel

Revel+mgo golang - How to define a struct type to handle nested objects coming from the db?


I have this kind of documents in my mongo collection -

{
    "_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
}

So there are several brands. I can get everything, except the category in this.

My Models code data type for this is -

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"`
}

I'm taking Category to be a string array right now but of course that's wrong.

The output looks like this -

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

How should I construct this struct to be able to display the kind of data I'm getting out from the database?


Solution

  • 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"`
    }