icz*_*cza 6

Id
bson:"_id,omitempty"
Id0int_idObjectId
Id0omitempty
intObjectIdIdinterface{}
Id interface{} `json:"_id,omitempty" bson:"_id,omitempty"`
int
intObjectIdbson.Getterbson.Setter

以下是如何使用自定义封送处理的示例:

IdBsonIdbson:"-"
type Booking struct {
        Id     int           `bson:"-"`
        BsonId bson.ObjectId `bson:"-"`
        TempId interface{}   `bson:"_id"`
        // rest of your fields...
}
TempId_id
GetBSON()TempIdSetBSON()TempId
func (b *Booking) GetBSON() (interface{}, error) {
    if b.Id != 0 {
        b.TempId = b.Id
    } else {
        b.TempId = b.BsonId
    }
    return b, nil
}

func (b *Booking) SetBSON(raw bson.Raw) (err error) {
    if err = raw.Unmarshal(b); err != nil {
        return
    }
    if intId, ok := b.TempId.(int); ok {
        b.Id = intId
    } else bsonId, ok := b.TempId.(bson.ObjectId); ok {
        b.BsonId = bsonId
    } else {
        err = errors.New("invalid or missing id")
    }

    return
}
TempIdBookingBookingtempBookingTempIdtempBookingtempBookingBooking