Reputation: 31237
We have a mongoose schema like this:
var sampleSchema = new Schema({
fieldABC: String,
expireAfter1Month:{
type: Date,
default: new Date() + 1 month
}
});
The default value of expireAfter1Month
shall be set to a date value after a month.
I have got these:
How to add month to current date in mongoose schema's default date value?
Probably I can do like
default: +new Date() + 30*24*60*60*1000
However, I wonder if there is any better/optimized approach?
Upvotes: 4
Views: 3513
Reputation: 1
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 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
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
Upvotes: 5