简体   繁体   中英

Save Unix Epoch Timestamp to Mongoose Schema type Date using NodeJS

I receive responses from the Stripe API GET /invoices endpoint that returns dates as unix timestamps. An example value is 1573917475. I need to save this value in an ISO Format in Mongoose. Example: 2019-11-16T15:17:55 I'm familiar with how to convert this value into a ISO / UTC formatted date time value using Javascript or MomentJS. However, I would like to set this behavior in the Mongoose Schema if possible.

API response containing timestamp values:

{
    "period_end": 1576509475,
    "period_start": 1573917475
}

Mongoose Schema:

new Schema({
 ... redacted ...
    period_end: { type: Date },
    period_start: { type: Date },
 ... redacted ...
});

This is currently saving the as dates in Mongo with values such as:

{
    "period_end": "1970-01-19T04:34:23.671+0000" 
}

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;
}

Mongoose supports setters/getters at the schema level which works with update ops.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM