Home > Backend Development > Golang > How to Define Default Dates in MongoDB Documents Using Go\'s Mgo?

How to Define Default Dates in MongoDB Documents Using Go\'s Mgo?

Mary-Kate Olsen
Release: 2024-11-22 17:03:53
Original
1050 people have browsed it

How to Define Default Dates in MongoDB Documents Using Go's Mgo?

Defining Default Dates in Mongo Documents with 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.

Custom Constructor with Default Value

One approach is to create a custom constructor function that populates the default value:

func NewUser() *User {
    return &User{
        CreatedAt: time.Now(),
    }
}
Copy after login

This ensures that every new User struct created using this constructor will have a default CreatedAt field.

Custom GetBSON Marshaler

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
}
Copy after login

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.

Considerations

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template