Golang struct中的AutoFill created_at和updated_at推入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)
如何使用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
MongoDB服务器不支持这一点。
您可以实施自定义元帅,可以在其中将这些字段更新为自己的喜好。实施
bson.marshaler
,当您保存
*用户
type的值时,将调用元号()
函数。这就是这样的样子:
注意该方法具有指针接收器,因此请使用指向您的值的指针:
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 yourMarshalBSON()
function will be called when you save values of your*User
type.This is how it would look like:
Note the method has pointer receiver, so use a pointer to your value:
The purpose of the
my
type is to avoid stack overflow.