如何为Mongoose Schema的calibrateDue字段设置默认值为当前日期+1年
解决Mongoose设备模型中calibrateDue字段默认值问题
嘿,我来帮你搞定这个默认值的设置问题~首先得指出你原代码里的两个小问题:
365 days不是合法的JavaScript语法,没法直接这么写- 注释的写法也有问题,会导致语法报错
要实现“当前日期加1年”的默认值逻辑,关键是要用函数作为默认值——因为如果直接写计算表达式,Mongoose只会在模型初始化的时候计算一次这个值,之后创建新文档都会用同一个固定时间;而用函数的话,每次创建新文档时都会重新执行函数,拿到最新的当前时间加一年的结果。
这里有两种靠谱的实现方式:
方式一:通过毫秒数计算(简洁版)
直接计算一年的毫秒数(按365天算),加到当前时间戳上:
const equipSchema = new mongoose.Schema({ dateConducted: { type: Date, default: Date.now }, calibrateDue: { type: Date, default: () => Date.now() + 365 * 24 * 60 * 60 * 1000 } }); module.exports = restful.model('Equipment', equipSchema);
方式二:用Date对象方法(精准处理闰年)
这种方式能自动处理闰年的特殊情况(比如2月29日的日期),逻辑更直观:
const equipSchema = new mongoose.Schema({ dateConducted: { type: Date, default: Date.now }, calibrateDue: { type: Date, default: () => { const currentDate = new Date(); currentDate.setFullYear(currentDate.getFullYear() + 1); return currentDate; } } }); module.exports = restful.model('Equipment', equipSchema);
两种方式都能满足需求,如果你不需要考虑闰年,方式一更简洁;如果需要精准适配闰年场景,方式二更合适。
内容的提问来源于stack exchange,提问作者Kleav James
相关产品推荐
相关产品推荐

