1

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?

1

1 Answer 1

1

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"`
}
3
  • This - type Category struct { ListName string bson:"listName" Slug string bson:"slug" } Returns this - { "ListName": "Trimmer/Epilator", "Slug": "trimmer" }, Whereas, this - type Category struct { ListName string json:"listName" Slug string json:"slug" } Returns this - {"listName": "", "slug": "trimmer" }, Which is actually closer to what I'd want. I want the field names to be there in the json just as they are. Aug 3, 2016 at 5:14
  • add bson:"listName" json:"listName" Aug 3, 2016 at 5:29
  • Please include this in the answer and I can mark it as correct! You're awesome! Aug 3, 2016 at 5:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.