Golang revel+mgo - 当结构变量具有小写名称时不返回数据

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

这是我的结构类型

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

与以下函数一起使用 return 来自 mongo 集合的所有结果 -

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

问题是我的数据库中的字段名称以小写字母开头,但当我尝试使用以小写字母开头的变量名称时,Golang 结构 returns null。例如这个 returns 一个 JSON 对应的字段为空 -

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

我实际上是在将基于 API 的 Meteor 移植到 Golang,目前使用 API 的许多产品都依赖于这些字段名称,就像它们在数据库中一样! 有解决方法吗?

您需要以首字母大写命名您的字段,使它们对 mgos bson Unmarshall 可见。您还需要映射到适当的 json/bson 字段名称

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