When accessing MongoDB from Go, you may encounter situations where you need to convert data types, such as handling dates stored as strings in MongoDB but requiring them as Go time.Time objects. Here's how to address this:
To handle type conversions during marshaling/unmarshaling between MongoDB and Go, implement custom logic using the bson.Getter and bson.Setter interfaces.
First, extend clientConfigData with an additional field EndDate of type time.Time:
type clientConfigData struct { SMTPAssoc int `bson:"smtp_assoc"` PlanType string `bson:"plan_type"` EndDateStr string `bson:"end_date"` EndDate time.Time `bson:"-"` }
Implement custom marshal/unmarshal logic in SetBSON() and GetBSON() methods:
const endDateLayout = "2006-01-02 15:04:05" 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 }
To avoid stack overflow, create a new intermediate my type within both methods, allowing conversion without endless recursion.
This custom marshaling and unmarshaling logic enables you to convert dates between string and time.Time formats when accessing MongoDB from Go.
The above is the detailed content of How to Handle Date Conversions When Accessing MongoDB from Go?. For more information, please follow other related articles on the PHP Chinese website!