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