【问题标题】:How to save a birthdate in Mongoose without throwing validation error如何在 Mongoose 中保存生日而不引发验证错误
【发布时间】:2019-06-20 22:37:47
【问题描述】:

在 Mongoose 的用户模型中,我有一个简单的 dob 字段,没有格式验证:

dob: {
    type: Date,
    alias: 'birthdate'
  },

在我的代码的其他地方,我将三个单独的用户输入字段格式化为日、月和年。我将其作为新的 Date() 返回,但格式为 YYYY-MM-DD 以避免任何奇怪的时区并发症。日期是日期和时间无关紧要。

exports.formatDob = function (day, month, year) {
  let dob = new Date( parseInt(year), parseInt(month) - 1, parseInt(day), 0, 0, 0, 0 );
  return new Date(dob, '<YYYY-MM-DD>');
}

当我尝试将此格式化日期保存到 Mongoose 中时,我在控制台中收到以下错误:

(node:32307) UnhandledPromiseRejectionWarning: ValidationError: User 验证失败:dob:Cast to Date 值“无效日期”失败 在路径“dob”

我做错了什么?

【问题讨论】:

    标签: node.js date mongoose mongoose-schema


    【解决方案1】:

    您可以使用Momentjs,在处理日期时总是推荐它。

    但是我们可以像使用 Date obj api 可用方法一样简单地解决这个问题,例如,如果我们想从 Date 对象返回格式 YYYY-MM-DD,我们可以执行以下操作:

    let dob = new Date( parseInt(year), parseInt(month) - 1, parseInt(day));
    return dob.getFullYear() + '-' + (dob.getMonth() + 1) + '-' + dob.getDate();
    

    let dob = new Date();
    console.log( dob.getFullYear() + '-' + (dob.getMonth() + 1) + '-' + dob.getDate() );

    请注意,我们已将 + 1 添加到 getMonth 方法,因为它返回 0-11 的值,而且我们已将此表达式添加到括号内,因此它不会被计算为字符串。

    【讨论】:

    • 很高兴它有帮助。
    猜你喜欢
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多