我正在使用time.Duration将数据存储在结构中,如下所示:

type ApiAccessToken struct {
    ...
    ExpiredIn   *time.Duration `bson:"expired_in,omitempty" json:"expired_in,omitempty"`
    ...
}

我使用这样的常量进行设置:
...
const ApiAccessTokenDefaultExpiresIn = 7 * 24 * time.Hour
...
d := ApiAccessTokenDefaultExpiresIn
data := &ApiAccessToken{
    ...
    ExpiredIn: &d
    ...
}
...

然后我使用mgo将数据插入数据库。

在创建data实例之后,插入数据之前,我确实进行了检查,并且ExpiredIn的值为604'800'000'000'000,但在MongoDB中,它变为604'800'000(或NumberLong(604800000))。

知道为什么吗?谢谢!

最佳答案

我们通常会为特定类型编写自定义的MarshalJSON / UnmarshalJSON,以控制在编组/解组之前/之后它们的值发生什么。

type ExpiredIn struct {
    time.Duration
}

func (e *ExpiredIn) MarshalJSON() ([]byte, error) {
    return []byte(string(e.Nanoseconds())), nil
}

func (e *ExpiredIn) UnmarshalJSON(data []byte) error {
    i, _ := strconv.ParseInt(string(data[:])), 10, 64)
    e.Duration = time.Duration(i)
    return nil

}

这是测试代码:
package main

import (
    "log"
    "time"

    "gopkg.in/mgo.v2"
)

type Token struct {
    ExpiredIn time.Duration
}

type ExpiredIn struct {
    time.Duration
}

func (e *ExpiredIn) MarshalJSON() ([]byte, error) {
    return []byte(string(e.Nanoseconds())), nil
}

func main() {
    session, err := mgo.Dial("mongodb://localhost:27017/test")
    if err != nil {
        panic(err)
    }
    defer session.Close()

    // Optional. Switch the session to a monotonic behavior.
    session.SetMode(mgo.Monotonic, true)

    c := session.DB("test").C("tokens")
    err = c.Insert(&Recipe{7 * 24 * time.Hour})
    if err != nil {
        log.Fatal(err)
    }
}

大功告成!

mongodb - 时间意外地将时间除以1'000'000-LMLPHP

关于mongodb - 时间意外地将时间除以1'000'000,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49955238/

10-12 12:35
查看更多