dshu1235
dshu1235
2016-08-03 04:09

Golang Revel + MGO-当结构变量的名称为小写时不返回任何数据

已采纳

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条回答

  • dongshan1959 dongshan1959 5年前

    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"`
    }
    
    点赞 评论 复制链接分享