gpt4 book ai didi

mongodb - 如何使用 mgo 从文档中解码命名类型别名?

转载 作者:IT王子 更新时间:2023-10-29 02:24:19 25 4
gpt4 key购买 nike

我有一个带有 updated_at 字段的结构,我想将其编码为 JSON 编码为 un​​ix 时间戳。

我尝试了以下似乎不起作用的方法,updated_at 字段永远不会从 MongoDB 文档中解码:

type Timestamp time.now

func (t Timestamp) MarshalJSON() ([]byte, error) {
ts := time.Time(t).Unix()
fmt.Println(ts)
stamp := fmt.Sprint(ts)

return []byte(stamp), nil
}


type User struct {
UpdatedAt *Timestamp `bson:"updated_at,omitempty" json:"updated_at,omitempty"`
}

我找到了一个临时解决方案,编写结构的 MarshalJSON 函数,执行如下操作(将 UpdatedAt 类型更改为 *time.Time):

func (u *User) MarshalJSON() ([]byte, error) {
out := make(map[string]interface{})

if u.UpdatedAt != nil && !u.UpdatedAt.IsZero() {
out["updated_at"] = u.UpdatedAt.Unix()
}

return json.Marshal(out)
}

是否有更好或更优雅的解决方案?

最佳答案

在其他地方找到了解决方案并写了一篇关于它的帖子 - https://medium.com/coding-and-deploying-in-the-cloud/time-stamps-in-golang-abcaf581b72f

要处理 mgo 的编码/解码,必须实现 GetBSON() 和 SetBSON() 函数。

关于mongodb - 如何使用 mgo 从文档中解码命名类型别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25661565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com