如何在不抛出验证错误的情况下在 Mongoose 中保存生日
How to save a birthdate in Mongoose without throwing validation error
在我的 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
validation failed: dob: Cast to Date failed for value "Invalid Date"
at path "dob"
我做错了什么?
您可以使用 Momentjs 在处理日期时始终推荐它。
然而,我们可以像使用 Date obj api 可用方法一样简单地解决这个问题,例如,如果我们想要 return 格式 YYYY-MM-DD
来自一个 Date 对象,我们可以执行以下操作:
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
方法,因为它 return 是 0-11 的值,而且我们已将此表达式添加到括号内,因此它不会被评估为字符串。
在我的 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 validation failed: dob: Cast to Date failed for value "Invalid Date" at path "dob"
我做错了什么?
您可以使用 Momentjs 在处理日期时始终推荐它。
然而,我们可以像使用 Date obj api 可用方法一样简单地解决这个问题,例如,如果我们想要 return 格式 YYYY-MM-DD
来自一个 Date 对象,我们可以执行以下操作:
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
方法,因为它 return 是 0-11 的值,而且我们已将此表达式添加到括号内,因此它不会被评估为字符串。