dshu1235 2016-08-03 04:09
浏览 68
已采纳

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 2016-08-03 04:25
    关注

    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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改