0

I need to remove mongodb documents after a specified period of not being accessed.

I have a access token I use to retrieve data from an external source and save it in my database.

In my session I store a user id I can use the retrieve the access token when a user makes a request.

If my session expires the access token saved in my database will never be used again.

The user will be prompted to re-authenticate and a new access token will be saved in the database.

If the user logs out explicitly I can easily remove the now invalid access token from the database. But if they never log out and the session expires then the database entry will remain indefinitely.

I thought about detect session expiry and run a function to remove the associated access token from my database but what if the session expires when app is not running.

I think I need some kind on maintenance like a cron job or something on my database that will remove documents after a specific period of not being accessed,

How would I go about this with mongoDB?

jalbasri
  • 318
  • 2
  • 13
  • 2
    Show a document definition of what you want to remove. But really you should be following [Expire Data from Collections by Setting TTL](http://docs.mongodb.org/manual/tutorial/expire-data/) which is direct from the online manual. – Blakes Seven Sep 22 '15 at 11:12
  • You can store `lastAccessTime` in each record(update it each time when you access it), run scheduler which remove all records whose `lastAccessTime` is more than specified period. – Harsh Patel Sep 22 '15 at 11:28
  • the document definition is simply { id: String, accessToken: String }, I don't think TTL is what I'm looking for as I want the document to remain if it is regularly being accessed. Just removed if it is inactive for specific period of time. I will look into scheduling jobs in nodejs (I've never done that before) and using lastAccessTime as suggested by HarshPatel – jalbasri Sep 22 '15 at 12:10

1 Answers1

0

Found this question that answer my question.

Basically set a TTL and update the creation date when the data is accessed achieve my desired behavior.

Community
  • 1
  • 1
jalbasri
  • 318
  • 2
  • 13