Home > Backend Development > Golang > How to Automatically Populate Created_at and Updated_at Fields in MongoDB using Go\'s BSON Marshaler?

How to Automatically Populate Created_at and Updated_at Fields in MongoDB using Go\'s BSON Marshaler?

DDD
Release: 2024-11-24 20:35:14
Original
920 people have browsed it

How to Automatically Populate Created_at and Updated_at Fields in MongoDB using Go's BSON Marshaler?

Automated Creation of Created_at and Updated_at Fields in MongoDB Using the Go Database Driver

In Go, when using the MongoDB database driver, the created_at and updated_at fields in a struct are not automatically populated with timestamps during insertions. To resolve this issue, a custom marshaler can be implemented to update these fields before saving the struct to MongoDB.

type User struct {
    ID           primitive.ObjectID `bson:"_id,omitempty"`
    CreatedAt    time.Time          `bson:"created_at"`
    UpdatedAt    time.Time          `bson:"updated_at"`
    Name         string             `bson:"name"`
}

func (u *User) MarshalBSON() ([]byte, error) {
    if u.CreatedAt.IsZero() {
        u.CreatedAt = time.Now()
    }
    u.UpdatedAt = time.Now()

    type my User
    return bson.Marshal((*my)(u))
}
Copy after login

The MarshalBSON() method is called when saving values of the *User type and ensures that the created_at and updated_at fields are set to the current time before marshaling the object into a BSON representation.

To use this custom marshaler, instantiate a pointer to your User object and insert it into the MongoDB collection:

user := &User{Name: "username"}

c := client.Database("db").Collection("collection")
if _, err := c.InsertOne(context.Background(), user); err != nil {
    // handle error
}
Copy after login

By implementing the MarshalBSON() method, you can automatically generate timestamps for the created_at and updated_at fields when saving a Go struct to MongoDB, ensuring the fields are properly populated with the current time.

The above is the detailed content of How to Automatically Populate Created_at and Updated_at Fields in MongoDB using Go's BSON Marshaler?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template