使用 NodeJS 将 Unix Epoch Timestamp 保存到 Mongoose Schema 类型 Date

And*_*lor 1 javascript mongoose mongodb node.js stripe-payments

我收到来自 Stripe API GET /invoices 端点的响应,该端点将日期作为 unix 时间戳返回。示例值为 1573917475。我需要将此值保存在 Mongoose 中的 ISO 格式中。示例:2019-11-16T15:17:55 我熟悉如何使用 Javascript 或 MomentJS 将此值转换为 ISO / UTC 格式的日期时间值。但是,如果可能,我想在 Mongoose Schema 中设置此行为。

包含时间戳值的 API 响应:

{
    "period_end": 1576509475,
    "period_start": 1573917475
}
Run Code Online (Sandbox Code Playgroud)

猫鼬架构:

new Schema({
 ... redacted ...
    period_end: { type: Date },
    period_start: { type: Date },
 ... redacted ...
});
Run Code Online (Sandbox Code Playgroud)

目前正在使用以下值保存 Mongo 中的 as 日期:

{
    "period_end": "1970-01-19T04:34:23.671+0000" 
}
Run Code Online (Sandbox Code Playgroud)

When the year is 1970 this is usually because an issue with the input date format. Can this type of conversion be performed at the Schema level ?

I saw this Mongoose documentation https://mongoosejs.com/docs/tutorials/dates.html that mentions converting the values before saving to the schema. But I would prefer not to loop thru the values manually as I'm saving the raw response from the API.

Edit: Using the answer provided by @ambianBeing I came up with the following solution.

new Schema({
 ... redacted ...
    period_end: { type: Date, set: d => convertSecsToMs(d) },
    period_start: { type: Date, set: d => convertSecsToMs(d) },
 ... redacted ...
});

function convertSecsToMs(d) {
  if (!d || !isValidTimestamp(d)) return;

  return new Date(d * 1000);
}

function isValidTimestamp(date) {
  return new Date(date).getTime() > 0;
}
Run Code Online (Sandbox Code Playgroud)

amb*_*ing 5

Mongoose 支持setters/getters与更新操作一起使用的模式级别。

const docSchema = new Schema({
  period_start: {
    type: Date,
    set: d => new Date(d * 1000)
  },
  period_end: {
    type: Date,
    set: d => new Date(d * 1000)
  }
});
Run Code Online (Sandbox Code Playgroud)