【问题标题】:How can I specificy Date without time in LoopBack 4 models?如何在 LoopBack 4 模型中指定没有时间的日期?
【发布时间】:2020-01-11 05:51:54
【问题描述】:

我正在使用 LoopBack 4 构建一个 API,在一个模型中有一个名为“day”的属性,它是一个 Date 类型(MySQL 列也是 Date 类型)。

但我不能向它发布像“2019-09-09”这样的值,因为它想要像“2019-09-09T12:41:05.942Z”这样的东西。 如何指定它必须是日期(没有时间)?

我很困惑,因为您可以在查询参数(日期类型)中传递“2019-09-09”,但不能在模型中传递。

我目前在模型中有这样的属性:

@property({
    type: Date,
    required: true,
    mysql: {
        columnName: 'day',
        dataType: 'date',
        dataLength: null,
        dataPrecision: null,
        dataScale: null,
        nullable: 'N',
    },
})
day: Date;

预期:接受“2019-09-09”作为值

其实:422:天应该匹配格式“日期-时间”

【问题讨论】:

  • 为什么不随时间发布呢? MySQL 会忽略它,对吧?
  • 我正在重建一个旧的 API,它可以接受没有时间的日子。如果 API 没有太大差异,那么使用旧 API 的旧客户端仍然可以使用新 API,这将非常有帮助。

标签: typescript loopback4


【解决方案1】:

我遇到了同样的问题,我使用 jsonSchema 指定请求 JSON 的格式解决了它。

在您的情况下,您必须通过以下方式更改代码:

@property({
    type: 'date', // Types in LoopBack4 are not case-sensitive so Date is the same than date
    jsonSchema: { 
      format: 'date', //This can be changed to 'date-time', 'time' or 'date'
    },
    required: true,
    mysql: {
        columnName: 'day',
        dataType: 'date',
        dataLength: null,
        dataPrecision: null,
        dataScale: null,
        nullable: 'N',
    },
})
day: string; // Change this also

【讨论】:

    【解决方案2】:

    类型应更改为'date' 而不是Date。这将允许更灵活的日期模式:

    @property({
        type: 'date',
        required: true,
        mysql: {
            columnName: 'day',
            dataType: 'date',
            dataLength: null,
            dataPrecision: null,
            dataScale: null,
            nullable: 'N',
        },
    })
    day: string;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-08
      • 2019-08-17
      • 2012-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多