Home > Backend Development > Golang > How to Automatically Add Created_at and Updated_at Timestamps to MongoDB Documents Using Go?

How to Automatically Add Created_at and Updated_at Timestamps to MongoDB Documents Using Go?

Susan Sarandon
Release: 2024-11-26 08:29:08
Original
662 people have browsed it

How to Automatically Add Created_at and Updated_at Timestamps to MongoDB Documents Using Go?

Adding Automated Created_at and Updated_at Fields in Golang Struct for MongoDB

Inserting data into MongoDB with a Go struct requires handling the automatic population of created_at and updated_at fields, a feature not inherently supported by the MongoDB server.

To address this, consider implementing a custom marshaler by implementing the bson.Marshaler interface. The MarshalBSON() function will be invoked upon persisting a value of the User type.

Here's a code snippet demonstrating the implementation:

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

Note that the MarshalBSON() method uses a pointer receiver, so it's necessary to use a pointer to the User instance.

Example usage:

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 employing this technique, you can automatically update created_at and updated_at fields when inserting or updating a MongoDB document via the Go struct.

The above is the detailed content of How to Automatically Add Created_at and Updated_at Timestamps to MongoDB Documents Using 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