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:
type clientConfigData struct { SMTPAssoc int `bson:"smtp_assoc"` PlanType string `bson:"plan_type"` EndDateStr string `bson:"end_date"` EndDate time.Time `bson:"-"` }
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.
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中文網其他相關文章!