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

How to Automate Created_at and Updated_at Timestamps in MongoDB using Go\'s BSON Marshaler?

DDD
DDDOriginal
2024-12-05 09:22:10234browse

How to Automate Created_at and Updated_at Timestamps in MongoDB using Go's BSON Marshaler?

Automating Created_at and Updated_at Field Population in MongoDB

In the provided Go code snippet, the User struct defines fields for _id, created_at, updated_at, and name. When a new User object is inserted into the database using InsertOne(), the created_at and updated_at fields are not automatically populated with timestamps.

Question: How can you use automated created_at and updated_at in the provided Go code with MongoDB using only the MongoDB driver?

Solution: The MongoDB server does not automatically handle auto-population of timestamps for these fields. However, you can implement this functionality manually by implementing a custom Marshaler for your User struct.

To create a custom Marshaler, implement the bson.Marshaler interface. The MarshalBSON() method will be called when values of the *User type are marshaled for insertion into the database.

Here's an example of how this can be implemented:

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

Note that the MarshalBSON() method has a pointer receiver, so you must use a pointer to the User value when inserting:

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

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

The purpose of the my type is to avoid stack overflow during the marshaling process.

The above is the detailed content of How to Automate Created_at and Updated_at Timestamps in MongoDB using Go\'s BSON Marshaler?. 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