golang氧化镁建模问题

问题描述 投票:1回答:1

我有这个模型数据,我用它来保存数据到数据库

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"`   
}

我的mongodb数据如下

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

使用golang package mgo我已经编写了以下代码来获取文档

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
}

我的响应为Reviews.reviewCommentsHistory返回null值。我的模型有问题吗?任何指针对于如何检查响应是否映射到我的模型都很有用

这是我的输出

{
"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"
}
go mgo
1个回答
0
投票

问题是,对于Nos.Reviews字段,您没有指定任何bson标记,这意味着将应用默认映射,这意味着字段名称将使用小写字母:"reviews"。但是你的MongoDB包含一个带大写字母的文件:"Reviews",因此映射将失败(解组将与MongoDB "Reviews"Nos.Reviews字段不匹配)。

指定缺少的标记:

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

它会奏效。

© www.soinside.com 2019 - 2024. All rights reserved.