Golang struct中的AutoFill created_at和updated_at推入MongoDB

发布于 2025-01-21 19:25:28 字数 524 浏览 0 评论 0原文

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"`
}

user := User{Name: "username"}

client.Database("db").Collection("collection").InsertOne(context.Background(), user)

如何使用Golang中的MongoDB(仅MongoDB驱动程序)在上述代码中使用自动化的Create_at和Updated_at?当前,它将为create_at和updated_at设置零时间(0001-01-01-01T00:00:00.000+00:00)。

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"`
}

user := User{Name: "username"}

client.Database("db").Collection("collection").InsertOne(context.Background(), user)

How to use automated created_at and updated_at in the above code with mongodb(mongodb driver only) in golang? Currently it will set zero time(0001-01-01T00:00:00.000+00:00) for created_at and updated_at.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云朵有点甜 2025-01-28 19:25:28

MongoDB服务器不支持这一点。

您可以实施自定义元帅,可以在其中将这些字段更新为自己的喜好。实施 bson.marshaler,当您保存*用户 type的值时,将调用元号()函数。

这就是这样的样子:

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

注意该方法具有指针接收器,因此请使用指向您的值的指针:

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


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

my类型的目的是避免堆栈溢出。

The MongoDB server does not support this.

You may implement a custom marshaler in which you may update these fields to your liking. Implement bson.Marshaler, and your MarshalBSON() function will be called when you save values of your *User type.

This is how it would look like:

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 the method has pointer receiver, so use a pointer to your value:

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


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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文