How to Handle Date Conversions When Accessing MongoDB from Go?

Mary-Kate Olsen
Release: 2024-11-23 11:00:56
Original
456 people have browsed it

How to Handle Date Conversions When Accessing MongoDB from Go?

Accessing MongoDB from Go: Working with Dates

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:

Custom Marshal/Unmarshal Logic

To handle type conversions during marshaling/unmarshaling between MongoDB and Go, implement custom logic using the bson.Getter and bson.Setter interfaces.

Customizing clientConfigData

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:"-"`
}
Copy after login

Implementing Custom Logic

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
}
Copy after login

Explanation

  • SetBSON(): Parses the EndDateStr field, setting the EndDate field as time.Time.
  • GetBSON(): Converts EndDate to a string in the specified format before saving.

Avoid Stack Overflow

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template