【问题标题】:MongoDB Stored my date with the wrong timeMongoDB 以错误的时间存储了我的日期
【发布时间】:2022-01-23 02:16:25
【问题描述】:

我最近尝试在 MongoDB 中分配一个新日期,但我有一个问题,它存储了我给出的日期但它不正确

userSchema.methods.createPasswordResetToken = async function () {
  this.passwordResetToken = crypto.randomBytes(20).toString('hex')
  this.passwordResetExpires = moment().format(this.createAt)

  await this.save()
  
  console.log(moment().format(this.createAt)) // 2021-12-21T19:01:54+02:00
  console.log(this.passwordResetExpires) // 2021-12-21T17:01:54.000Z 
  
  return { token: this.passwordResetToken, userId: this._id }
}

mongoDb 存储时删除 2 小时

当我试图捕捉两个值的类型时 我得到了

  console.log(moment().format(this.createAt)) // string
  console.log(this.passwordResetExpires) // object 

用户架构

...
passwordResetToken: String,
passwordResetExpires: Date
...

【问题讨论】:

  • 不要将日期作为字符串传递,使用this.passwordResetExpires = moment().toDate()
  • 什么是this.createAt

标签: javascript node.js mongodb express momentjs


【解决方案1】:

来自docs

默认情况下,MongoDB 以 UTC 存储时间,并将任何本地时间表示形式转换为这种形式。必须对某些未修改的本地时间值进行操作或报告的应用程序可以将时区与 UTC 时间戳一起存储,并在其应用程序逻辑中计算原始本地时间。

您的服务器似乎只是位于 GMT 时区(UTC +2,您也可以从您的日期值 // 2021-12-21T19:01:54+02:00 中看到它)。我通常会提供一些技巧来解决这个问题,但这实际上是一个最佳实践。因此,我建议您使用 UTC 而不是机器时间来计算日期。

  • 请注意您的其他日期是 UTC (2021-12-21T17:01:54.000Z),请确保您将苹果与苹果进行比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 2016-11-18
    相关资源
    最近更新 更多