Home >Backend Development >Golang >How to Define Default Dates in MongoDB Documents Using Go\'s Mgo?
In MongoDB, it's common to define default timestamps for document fields. However, in Go with Mgo, there's no direct way to set default values for fields.
One approach is to create a custom constructor function that populates the default value:
func NewUser() *User { return &User{ CreatedAt: time.Now(), } }
This ensures that every new User struct created using this constructor will have a default CreatedAt field.
Another option is to implement a custom serialization logic using BSON's bson.Getter interface:
func (u *User) GetBSON() (interface{}, error) { if u.CreatedAt.IsZero() { u.CreatedAt = time.Now() } type my *User return my(u), nil }
When marshalling the User to BSON, this GetBSON function will be invoked and populate the CreatedAt field with the current time if it's not already set.
Note that with either approach, the CreatedAt field will be overwritten with the current time even when updating an existing document. To avoid this, you can add a check in GetBSON to only set the field if it's the zero value.
Additionally, the custom marshaling approach requires you to implement bson.Getter for any type that contains a time.Time field with a default value.
The above is the detailed content of How to Define Default Dates in MongoDB Documents Using Go's Mgo?. For more information, please follow other related articles on the PHP Chinese website!