首页 文章

在mongoose模式的默认日期值中将月份添加到当前日期

提问于
浏览
3

我们有一个像这样的猫鼬模式:

var sampleSchema = new Schema({
    fieldABC: String,
    expireAfter1Month:{
        type: Date,
        default: new Date() + 1 month
    }
});

expireAfter1Month 的默认值应设置为一个月后的日期值 .

我有这些:

如何在mongoose模式的默认日期值中添加月份到当前日期?

也许我可以这样做

default: +new Date() + 30*24*60*60*1000

但是,我想知道是否有更好/优化的方法?

1 回答

  • 4

    基于您发布的其中一个链接的答案

    https://stackoverflow.com/a/30525690/5053002

    var minuteFromNow = function(){
        var timeObject = new Date();
        timeObject.setTime(timeObject.getTime() + 1000 * 60);
        return timeObject;
    };
    
    new Schema({
        date: { type: Date, default: minuteFromNow }
    })
    

    例如,如果你想要的话,从1月29日/ 30日/ 31日到2月28日(当然是闰年29日),从3月31日,5月,8月或10月到3月30日,6月,9月,一个月和11月分别,你需要更多的逻辑

    就像是

    function oneMonthFromNow() {
        var d = new Date();
        var targetMonth = d.getMonth() + 1;
        d.setMonth(targetMonth);
        if(d.getMonth() !== targetMonth % 12) {
            d.setDate(0); // last day of previous month
        }
        return d;
    }
    new Schema({
        date: { type: Date, default: oneMonthFromNow}
    })
    

    为了说明这将如何处理月末,以下是相同的代码,除了 d 是传入的任意日期,而不是使用 now - 来说明这将如何工作

    function oneMonthFromNow(d) {
        var targetMonth = d.getMonth() + 1;
        d.setMonth(targetMonth);
        if(d.getMonth() !== targetMonth % 12) {
            d.setDate(0); // last day of previous month
        }
        return d;
    }
    console.log(oneMonthFromNow(new Date('2017-10-31T00:00:00Z'))); // 30 November
    console.log(oneMonthFromNow(new Date('2017-11-30T00:00:00Z'))); // 30 December
    console.log(oneMonthFromNow(new Date('2017-12-31T00:00:00Z'))); // 31 January
    console.log(oneMonthFromNow(new Date('2018-01-31T00:00:00Z'))); // 28 February
    console.log(oneMonthFromNow(new Date('2018-02-28T00:00:00Z'))); // 28 March
    

    你的评论(在我发布这个答案之后添加:p)建议从1月31日起的一个月应该是3月2日,即总是只增加30天,在这种情况下你自己的建议

    new Schema({
        date: { type: Date, default: +new Date() + 30*24*60*60*1000}
    })
    

    会是理想的

相关问题