【问题标题】:Mongoose custom SchemaType toJSON/TransformMongoose 自定义 SchemaType toJSON/Transform
【发布时间】:2020-03-29 12:55:44
【问题描述】:

对于我目前正在处理的应用程序,我需要存储没有时间的日期。我通过创建一个看起来像这样的自定义模式类型来做到这一点:

var mongoose = require('mongoose');

/**
 * Registers a new DateOnly type field. Extends the `Date` Schema Type
 */
function DateOnly(key, options) {
  mongoose.SchemaTypes.Date.call(this, key, options, 'DateOnly');
}

DateOnly.prototype = Object.create(mongoose.SchemaTypes.Date.prototype);

DateOnly.prototype.cast = (originalValue) => {
  try {
    var value = originalValue;
    if (typeof value === 'string' && !value.match(/^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))(T00:00:00.000Z)?$/)) {
      throw new Error('Date is invalid');
    } else if (typeof value === 'number') {
      value = new Date(value);
    }

    if (value instanceof Date) {
      value = new Date(value.getFullYear(), value.getMonth(), value.getDate());
    }

    return mongoose.Schema.Types.Date._cast(value);
  } catch (err) {
    throw new mongoose.SchemaType.CastError('date', originalValue, this.path);
  }
};

mongoose.Schema.Types.DateOnly = DateOnly;

module.exports = DateOnly;

这允许模型接受日期字符串(例如:2020-01-01)和日期对象。现在这将在 UTC 时间午夜存储所有日期,这样我仍然可以获得将它们作为日期存储在 mongodb 中的所有优势。

我的问题在于,当我将这些日期之一返回到 API 时,它会以完整的 ISO 格式(例如:2020-01-01T00:00:00.000Z)返回,这将被转换为本地用户的时区。在我的时区中,此日期将显示为比预期提前 1 天。

所以我的问题是,我怎样才能使它在调用 document.toJSON 时转换日期?我知道我想要返回的是date.toISOString().substring(0,10)。

我尝试从 Date 类继承,但我发现它与 mongoose 和 mongodb 驱动程序的工作方式不兼容。

我知道我可以编写一个方法来放入 toJSON.transform 选项,但是我必须为每个使用该类型的字段和模型执行此操作。

【问题讨论】:

  • 你考虑过使用 Moment 吗?
  • var moment = require('moment'); moment().format();
  • 那么你可以使用例如.... moment().format('YYYY MM DD');
  • 我看不出这与我的问题有什么关系。我如何格式化日期并没有什么不同,这不是问题。

标签: node.js mongodb express mongoose


【解决方案1】:

在 mongoose 5.9.0 中添加了一个解决方案,可以这样做:

DateOnly.set('transform', (val) => {
  return /* transformed value */;
});

来源:https://github.com/Automattic/mongoose/issues/8403

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 2012-04-17
    相关资源
    最近更新 更多