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
  • Also, please do not ignore errors. Collection(s).Find(bson.M{}).All(&results) should check for the returned value ( type error ) to be nil. blog.golang.org/error-handling-and-go Commented Aug 3, 2016 at 5:40

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"`
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
add bson:"listName" json:"listName"
Please include this in the answer and I can mark it as correct! You're awesome!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.