Add month to current date in mongoose schema's default date value Add month to current date in mongoose schema's default date value mongoose mongoose

Add month to current date in mongoose schema's default date value


Building on the answer to one of the links you posted

i.e. 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 }})

If you want, for example, one month from 29th/30th/31st January to all be 28th February (29th in leap years of course), and one month from 31st March, May, August or October to be 30th April, June, September and November respectively, then you need a little more logic

Something like

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}})

To illustrate how that would handle end of month, the following is the same code, except d is an arbitrary date passed in, rather than using now - to show how this will work

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 Novemberconsole.log(oneMonthFromNow(new Date('2017-11-30T00:00:00Z'))); // 30 Decemberconsole.log(oneMonthFromNow(new Date('2017-12-31T00:00:00Z'))); // 31 Januaryconsole.log(oneMonthFromNow(new Date('2018-01-31T00:00:00Z'))); // 28 Februaryconsole.log(oneMonthFromNow(new Date('2018-02-28T00:00:00Z'))); // 28 March