Home > Article > Backend Development > 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)) }
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 }
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!