Search code examples
mongodbgostructmgorevel

Golang revel+mgo - no data returned when struct variables having lowercase names


This is my struct type

type Category struct {
    Name string     `bson:"listName"`
    Slug string     `bson:"slug"`
}

used with the following function to return all results from a mongo collection -

func GetCategories(s *mgo.Session) []Category {
    var results []Category
    Collection(s).Find(bson.M{}).All(&results)
    return results
}

The problem is that the field names in my db have names starting in lowercase but the Golang struct returns null when I try to use variable names starting with lower case. For e.g. this returns a JSON with corresponding fields empty -

type Category struct {
    listName string `bson:"listName"`
    slug string     `bson:"slug"`
}

I'm actually porting a Meteor based API to Golang and a lot of products currently using the API rely on those field names like they are in the db! Is there a workaround?


Solution

  • You need to make your fields visible for mgos bson Unmarshall by naming them with a starting capital letter. You also need to map to the appropiates json/bson field names

    type Category struct {
        ListName string      `json:"listName" bson:"listName"`
        Slug string          `json:"slug"     bson:"slug"`
    }