0

My goal is to prevent an email from being sent more than once in a 24 hour period. I have a schema:

var requestSchema = new mongoose.Schema({
    email: String,
    lastSent: Date
});

In my Express route I'm testing to see if the lastSent variable is more than one day ago...

var lastSent = new Date(existingRequest.lastSent);
var nextDate = new Date() - 1;

if (lastSent > nextDate) {
    if (constants.dev){ console.log('Signup request too soon'); }
} else {
    // Process request
}

... however I cannot seem to catch the date. Logging the dates to the Express console shows this:

Last Sent: Tue Dec 16 2014 10:12:54 GMT-0500 (Eastern Standard Time)
Threshold: 1418746385786

Is there a chance that the date formats are mismatched?

Ryan D'Baisse
  • 837
  • 11
  • 29

1 Answers1

1
  1. The conversion of the ISODate coming from MongoDB is not necessary

  2. You need to subtract in milliseconds, so you need to subtract 24*60*60*1000 to subtract a whole day.

  3. The subtraction will return a timestamp, so you won't be able to use the usual Date functions on that - you will need to construct a new date from the timestamp.

Try:

var nextDate = new Date(new Date() - 24*60*60*1000);
if(existingRequest.lastSent > nextDate) {...}
Community
  • 1
  • 1
Laura
  • 3,233
  • 3
  • 28
  • 45
  • Perfect! Thanks! The double-convert was the trick. I had originally started subtracting milliseconds, so that was a snap to replace. The conversion was the part that was causing my brain to hurt. =) – Ryan D'Baisse Dec 16 '14 at 17:45