[英]Save Unix Epoch Timestamp to Mongoose Schema type Date using NodeJS
我收到来自 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
}
猫鼬架构:
new Schema({
... redacted ...
period_end: { type: Date },
period_start: { type: Date },
... redacted ...
});
目前正在使用以下值保存 Mongo 中的 as 日期:
{
"period_end": "1970-01-19T04:34:23.671+0000"
}
当年份为 1970 时,这通常是因为输入日期格式存在问题。 这种类型的转换可以在 Schema 级别执行吗?
我看到了这个 Mongoose 文档https://mongoosejs.com/docs/tutorials/dates.html ,其中提到在保存到架构之前转换值。 但是我不想手动循环遍历这些值,因为我正在保存来自 API 的原始响应。
编辑:使用@ambianBeing 提供的答案,我想出了以下解决方案。
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 在模式级别支持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)
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.