doujiong2533 2018-03-05 13:01
浏览 63
已采纳

golang mgo建模问题

I have this model data which I use to save data to the database

type Nos struct {
  UnitCode       string    `json:"unitCode" bson:"unitCode"`    
  Version        string    `json:"version" bson:"version"`

  Reviews struct {
    ReviewCommentsHistory []reviewCommentsHistory `json:"reviewCommentsHistory" bson:"reviewCommentsHistory"`
}
  ID        bson.ObjectId `bson:"_id"`
  CreatedAt time.Time     `bson:"created_at"`
  UpdatedAt time.Time     `bson:"updated_at"`
}

type reviewCommentsHistory struct {
    ReviewHistoryDate time.Time `json:"reviewHistoryDate" bson:"reviewHistoryDate,omitempty"`   
}

My mongodb data is as follows

{
"_id" : ObjectId("5a992d5975885e236c8dc723"),
"unitCode" : "G&J/N3601",
"version" : "3",    
"Reviews" : {
    "reviewCommentsHistory" : [ 
        {
            "reviewHistoryDate" : ISODate("2018-04-28T18:30:00.000Z")              
        }
    ]
}
}

Using golang package mgo I have written the following piece of code to get the document

func (nosDal NosDal) FindNos(unitCode string, version string) ([]model.Nos, error) {
    var result []model.Nos
    var err error
    col := repository.DB.C("nos")   
    err = col.Find(bson.M{"unitCode": strings.ToUpper(unitCode), "version": version}).All(&result)
    fmt.Println(result[0])
    return result, err
}

My response returns the value of null for Reviews.reviewCommentsHistory. Is there an issue with my model? Any pointers would be useful on how to check if the response is mapping to my model

This is my output

{
"unitCode": "G&J/N3601",    
"version": "3",    
"Reviews": {
    "reviewCommentsHistory": null
},
"ID": "5a992d5975885e236c8dc723",
"CreatedAt": "2018-03-02T16:24:17.19+05:30",
"UpdatedAt": "2018-03-05T18:04:28.478+05:30"
}
  • 写回答

1条回答 默认 最新

  • dongsuishou8039 2018-03-05 13:20
    关注

    The problem is that for the Nos.Reviews field you did not specify any bson tag, which means the default mapping will be applied, which means the field name will be used with lowercase letter: "reviews". But your MongoDB contains the document with a capital letter: "Reviews", so the mapping will fail (unmarshaling will not match the MongoDB "Reviews" to the Nos.Reviews field).

    Specify the missing tag:

    Reviews struct {
        ReviewCommentsHistory []reviewCommentsHistory `json:"reviewCommentsHistory" bson:"reviewCommentsHistory"`
    } `json:"Reviews" bson:"Reviews"`
    

    And it will work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况