首頁 > 後端開發 > Golang > 如何在 Go 中自訂 MongoDB 類型的編組/解組?

如何在 Go 中自訂 MongoDB 類型的編組/解組?

DDD
發布: 2024-11-15 02:05:03
原創
502 人瀏覽過

How to Customize Marshaling/Unmarshaling for MongoDB Types in Go?

Customizing Marshaling/Unmarshaling for MongoDB Types in Go

When accessing MongoDB from Go, you may encounter situations where values need to be transformed during marshaling/unmarshaling. Consider the case of accessing the EndDate field stored as a string in MongoDB, but you require it as a Go time.Time type.

To address such scenarios, you can implement custom marshaling/unmarshaling logic using the bson.Getter and bson.Setter interfaces. Here's a step-by-step guide:

  1. Extend the Data Structure: Extend the clientConfigData type by adding a new field of type time.Time, denoted with a bson tag of "-".
type clientConfigData struct {
    SMTPAssoc  int       `bson:"smtp_assoc"`
    PlanType   string    `bson:"plan_type"`
    EndDateStr string    `bson:"end_date"`
    EndDate    time.Time `bson:"-"`
}
登入後複製
  1. Implement Custom Marshaling/Unmarshaling: Create SetBSON() and GetBSON() methods to handle custom marshaling/unmarshaling.
const endDateLayout = "2006-01-02 15:04:05" // Specify your preferred date layout

func (c *clientConfigData) SetBSON(raw bson.Raw) (err error) {
    type my clientConfigData
    if err = raw.Unmarshal((*my)(c)); err != nil {
        return
    }
    c.EndDate, err = time.Parse(endDateLayout, c.EndDateStr)
    return
}

func (c *clientConfigData) GetBSON() (interface{}, error) {
    c.EndDateStr = c.EndDate.Format(endDateLayout)
    type my *clientConfigData
    return my(c), nil
}
登入後複製

In SetBSON(), populate the struct with the raw MongoDB value and parse the EndDateStr into a time.Time. In GetBSON(), set the EndDateStr and return.

  1. Use Custom Marshaling/Unmarshaling:

When finding or inserting documents, remember to use the custom marshaling/unmarshaling logic by specifying the clientConfigData type.

var configRes = new(clientConfigData)
err := clientDB.
    C(clientConfigCollection).
    Find(bson.M{}).
    One(&configRes)
if err != nil {
    return nil, errors.Wrap(err, "finding config collection")
}
登入後複製

By implementing custom marshaling/unmarshaling, you can seamlessly work with MongoDB values that require specific type conversions. Remember to handle both SetBSON() and GetBSON() to cover both marshalling and unmarshalling.

以上是如何在 Go 中自訂 MongoDB 類型的編組/解組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板