Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Checking the last time a request has been made, deleting stuff from database if the time exceeds a minute

I’m trying to make a timer that would check when the last request to a specific path was made and if the last request was made more than a minute ago, I want the script to delete a document from a mongodb database.

I’ve tried to achieve this with sessions, but I haven’t been successful doing so. I’ve also tried to save the current time to the DB with the request and then checking it, but I don’t know how to make the timer "run in the background", if that’s even possible. I also want the timer to run per every ID (the ID is included in a table with the request)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using a TTL index may help you. It would allow you to set an expiry date for documents when they are accessed, and MongoDB will take care of deleting them after the time is up.

Add a TTL index to your database:

db.entites.createIndex({ requestedAt: 1 }, { expireAfterSeconds: 60 });

When a request is made, update the documents you want to expire by setting the current date for the indexed field:

db.entites.updateMany({ requestId }, { $set: { requestedAt: new Date() } });

Any documents with the requestedAt field set, will be deleted 60 seconds after it’s set timestamp.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading