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.

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

报告相同问题?