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.

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么