繁体   English   中英

在推入 mongodb 时自动填充 golang 结构中的 created_at 和 updated_at

[英]Autofill created_at and updated_at in golang struct while pushing into 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"`
}

user := User{Name: "username"}

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

如何在上述代码中使用自动 created_at 和 updated_at 和 golang 中的 mongodb(仅限 mongodb 驱动程序)? 目前它将为 created_at 和 updated_at 设置零时间(0001-01-01T00:00:00.000+00:00)。

MongoDB 服务器不支持这个。

您可以实现自定义封送拆收器,您可以在其中根据自己的喜好更新这些字段。 实现bson.Marshaler ,当您保存*User类型的值时,将调用MarshalBSON()函数。

这就是它的样子:

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类型的目的是避免堆栈溢出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM