ani0710 ani0710 - 6 months ago 61
Node.js Question

Mongoose: increment the date field of a mongo collection by one month

I need to update a date field of a mongo collection by day, week and month according to the requirement. I figured it out for day and week with the below code:

Set next day:

col.findOneAndUpdate(
{ _id : item._id }
, { $set : { nextRun : new Date(item.nextRun.getTime() + 86400000}}


Set same day for next week:

col.findOneAndUpdate(
{ _id : item._id }
, { $set : { nextRun : new Date(item.nextRun.getTime() + (86400000*7))}}


How to update for month in the similar fashion?

Note: I don't want to multiply with 30 as the updated field would be one day lesser if the current month has 31 days.

for e.g. if the field has value 2016-05-24T11:30:00.000Z , then the update should change it to 2016-06-24T11:30:00.000Z.

Tried with getMonth() but it didn't work.

Answer

Add the month as follows:

var nextRunDate = new Date(item.nextRun);
nextRunDate.setMonth(nextRunDate.getMonth() + 1);
col.findOneAndUpdate(
    { _id : item._id }, 
    { $set : { nextRun : nextRunDate } }
);

A much better approach would be to use a date handling library like moment, where you can use the add() method

var nextRunDate = moment(item.nextRun).add(1, 'months').toDate();
col.findOneAndUpdate(
    { _id : item._id }, 
    { $set : { nextRun : nextRunDate } }
);