【发布时间】:2018-08-23 07:12:20
【问题描述】:
我正在开发一个结合使用 Go 和 MongoDB 的项目。我被困在一个我有这样一个结构的地方:
type Booking struct {
// booking fields
Id int `json:"_id,omitempty" bson:"_id,omitempty"`
Uid int `json:"uid,omitempty" bson:"uid,omitempty"`
IndustryId int `json:"industry_id,omitempty" bson:"industry_id,omitempty"`
LocationId int `json:"location_id,omitempty" bson:"location_id,omitempty"`
BaseLocationId int `json:"base_location_id,omitempty" bson:"base_location_id,omitempty"`
}
在这个结构中,字段Id 是int 类型。但是我们知道 MongoDB 的默认 id 是 bsonObject 类型。有时,系统会在Id字段中生成默认的MongoDB id。
为了克服这个问题,我修改了这样的结构:
type Booking struct {
// booking fields
Id int `json:"_id,omitempty" bson:"_id,omitempty"`
BsonId bson.ObjectId `json:"bson_id" bson:"_id,omitempty"`
Uid int `json:"uid,omitempty" bson:"uid,omitempty"`
IndustryId int `json:"industry_id,omitempty" bson:"industry_id,omitempty"`
LocationId int `json:"location_id,omitempty" bson:"location_id,omitempty"`
BaseLocationId int `json:"base_location_id,omitempty" bson:"base_location_id,omitempty"`
}
在上面的结构中,我在两个不同的结构字段 Id(int 类型)和 BsonId(bson.ObjectId)中映射了相同的 _id 字段。我想如果整数类型的 id 来了,它映射在Id 下,否则在BsonId 下。
但是这个东西给出了以下错误:
Duplicated key '_id' in struct models.Booking
如何使用 Go Structs 实现这种类型的东西??
更新:
这是我为自定义编组/解组编写的代码:
func (booking *Booking) SetBSON(raw bson.Raw) (err error) {
type bsonBooking Booking
if err = raw.Unmarshal((*bsonBooking)(booking)); err != nil {
return
}
booking.BsonId, err = booking.Id
return
}
func (booking *Booking) GetBSON() (interface{}, error) {
booking.Id = Booking.BsonId
type bsonBooking *Booking
return bsonBooking(booking), nil
}
但这会导致 Id 和 BsonId 字段的类型不匹配错误。我现在该怎么办?
【问题讨论】: