Home > database >  Is there an efficient way of checking if a date has passed in a database automatically using JavaScr
Is there an efficient way of checking if a date has passed in a database automatically using JavaScr

Time:12-08

I’m fairly new to backend development in Node JS. I am currently working on a membership system for users where each user can get a membership for a limited amount of time. My database of choice is MongoDB and I’m using mongoose to interact with it (don’t know if that matters). Let's say I store the start and end date of a user membership based on how they signed up, what would be an efficient way of checking when a membership has come to an end? Should you use a function like setInterval which checks every 1-5 seconds or would that be inefficient? Is there a good way to go about this?

My idea was to use the setInterval function and run that every 2 seconds. However, I’m worried that could be very inefficient as the code would have to constantly retrieve information from the database every 2 seconds and run a lot of validations. Is this how it's actually done or is there any better way to go about it?

CodePudding user response:

I think there is a lot of ambiguity and opinion in this question, hence the downvotes.

A resource effective way of handling this would typically be:

  • Store membership expiry times in database
  • Set up a method / function that does something with a given expired user (email, archive, delete, whatever), let's call this the 'ExpireMe' function.
  • When a user requests an action (login, access a service etc), check that they are valid, if they are great, if not call the ExpireMe function and don't let them access anything
  • Set up a service that will periodically check for expired users, lets say, once a day, twice a day, but NEVER every 2 seconds. For every user it finds that has expired, run the ExpireMe function against that user. Always ensure that this service is only running on one node if you have multiple servers.

CodePudding user response:

Came across the package node-cron that I think would seem to be helpful in my case.

Edit: This helped me in my case? What's with the unjustified downvotes here on SO? If you think that's a problem with my solution please elaborate. I would love to know more about where I am wrong.

  • Related