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
Your comment (added after I posted this answer :p) suggests one month from Jan 31 should be Mar 2, i.e. always just add 30 days, in that case your own suggestion
new Schema({ date: { type: Date, default: +new Date() + 30*24*60*60*1000}})
would be ideal