Home >Backend Development >Golang >How to Automate Created_at and Updated_at Timestamps in MongoDB using Golang?

How to Automate Created_at and Updated_at Timestamps in MongoDB using Golang?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 13:17:111015browse

How to Automate Created_at and Updated_at Timestamps in MongoDB using Golang?

Automating Created_at and Updated_at Fields in MongoDB with Golang

In the provided code snippet, the User struct lacks automation for the created_at and updated_at fields. These fields are crucial for tracking temporal events.

Solution

The MongoDB server lacks support for automated field population. To achieve this, you can implement a custom marshaling function for the User struct. By implementing the bson.Marshaler interface, you can control how the struct is serialized into BSON.

Implementation

Here's how you can implement the MarshalBSON function:

import (
    "context"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
)

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))
}

You must note that the MarshalBSON function has a pointer receiver, and you must use a pointer to your User value when marshaling.

Usage

After implementing the custom marshaling function, you can use it like this:

client := mongo.NewClient(...) // (redacted for brevity)

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

Explanation

The MarshalBSON function checks if the created_at field is empty and sets it to the current time if so. It then sets the updated_at field to the current time. By using a type alias (my) and casting the User struct to *my, you avoid potential stack overflow during the marshalling process.

The above is the detailed content of How to Automate Created_at and Updated_at Timestamps in MongoDB using Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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