douyujun0152
2018-12-13 17:05
浏览 273

在MongoDB中保存纳秒级时间戳(由Go生成,使用Node.js保存)

I am trying to store Unix timestamps in nanoseconds into the Date type field of a Mongodb database.

The unix timestamps in nanoseconds are generated in a Go program (with time.Now().UnixNano()), submitted to Kafa to be read by a Node.js script which uses mongoose to write the payload object containing the unix timestamp in nanoseconds to the Mongodb store.

However this is throwing an error

UnhandledPromiseRejectionWarning: ValidationError: trade validation failed: timestamp: Cast to Date failed for value "1544720051987010000" at path "timestamp"

Is there a better way to store unix timestamps in nanosecond in Mongodb?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试将Unix时间戳(以纳秒为单位)存储到Mongodb的 Date 类型字段中

在Go程序(使用 time.Now()。UnixNano())中生成以十亿分之一秒为单位的unix时间戳,并提交给Kafa进行读取 由Node.js脚本使用 mongoose 将包含unix时间戳的有效负载对象(以纳秒为单位)写入Mongodb存储。

但这会引发错误< / p>

UnhandledPromiseRejectionWarning:ValidationError:交易验证失败:timestamp:在日期“ timestamp”的值“ 1544720051987010000”的强制转换为Date \ n

在Mongodb中是否有更好的方法来存储以ns为单位的unix时间戳?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzong8110 2018-12-13 17:45
    已采纳

    I am trying to store Unix timestamps in nanoseconds into the Date type field of a Mongodb database. Nyxynyx

    That is not going to work.


    Internally, Date objects are stored as a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970).

    MongoDB Reference: Date()


    For example,

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        timestamp := time.Now().UnixNano() / int64(time.Millisecond)
        fmt.Println(timestamp)
    }
    

    Playground: https://play.golang.org/p/21S_DeVA4jv

    Output:

    1257894000000
    

    To store Unix nanoseconds, use the long data type.

    点赞 评论

相关推荐 更多相似问题