【问题标题】:How to work with Date and Time in NodeJS, Mongoose and TypeScript?如何在 NodeJS、Mongoose 和 TypeScript 中使用日期和时间?
【发布时间】:2019-05-23 06:02:17
【问题描述】:

我来自 java 世界,我从 NodeJS 开始。 我很难理解如何在 NodeJS 中处理日期和时间。

只有日期和小时。

这是一个例子:

export interface teste extends mongoose.Document {
    description: string,
    dateTest: ????,
    openingTime: ????,
    finalTime: ????,
    dateTimeRecord: ????
}

const testeSchema = new mongoose.Schema({
    description:{
        type: String,
        required: true,
        maxlength: 200,
        minlength: 3
    },
    dateTest:{
        type: ?????,
        required: true
    },
    openingTime:{
        type: ?????,
        required: true
    },
    finalTime:{
        type: ?????,
        required: true
    },
    dateTimeRecord:{
        type: ?????,
        required: true
    }
}

export const Teste = mongoose.model<Teste>('Teste', testeSchema)

在我离开的所有地方?????我不知道该放什么。

  • 在 dateTest 中,我只需要记录日期,而不需要记录时间。
  • 在 openingTime 和 finalTime 中,我只需要存储小时数,没有日期。
  • 在 dateTimeRecord 中,我需要存储发生某事的时刻(日期和时间)。

如何做到这一点?

【问题讨论】:

    标签: node.js mongodb typescript mongoose mongoose-schema


    【解决方案1】:

    Mongoose 有一个Date 类型。 (Docs here) 替换 ???和Date 一起,你应该准备好了。

    【讨论】:

      【解决方案2】:

      在 Mongoose 中,你有一个 Date 类型 您可以设置默认日期(实际上它使用 ISODate) 你可以这样编码

      const testeSchema = new mongoose.Schema({
          description:{
              type: String,
              required: true,
              maxlength: 200,
              minlength: 3
          },
          dateTest:{
              type: Date,
              default:Date.now // this sets the default date time stamp using proper ISODate format
              required: true
          },
          openingTime:{
              type: Date,
              required: true
          },
          finalTime:{
              type: Date,
              required: true
          },
          dateTimeRecord:{
              type: Date,
              required: true
          }
      }
      

      您可以在猫鼬文档here中阅读更多内容

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-13
        • 1970-01-01
        • 1970-01-01
        • 2016-11-19
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 2011-11-30
        相关资源
        最近更新 更多