skip to Main Content

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)

2

Answers


  1. 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.

    Login or Signup to reply.
  2. Here is an option you can try:

    For each request store some details in variable called last_request_time, e.g., timestamp. The last_request_time value gets updated for each request.

    Run a cron job – the background job runs every 10 seconds (or 15, 20, or 30 secs). See node-cron.

    The job:

    Calculate difference of current_time and last_request_time
    If difference is greater then 60 seconds:
        Set the last_request_time value to null
        Delete document from database
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search