Mongoid document Time to Live
mongoid, ruby-on-rails
Solution
MongoDB (version 2.2 and up) actually has a special index type that allows you to specify a TTL on a document (see http://docs.mongodb.org/manual/tutorial/expire-data/). The database removes expired documents for you--no need for cron jobs or anything.
Mongoid supports this feature as follows:
index({created_at: 1}, {expire_after_seconds: 1.week})
The `created_at` field must hold date/time information. Include `Mongoid::Timestamps` in your model to get that for free.
UPDATE:
If you want to expire only a subset of documents, then you can create a special date/time field that is only populated for that subset. Documents with no value or a non-date/time value in the indexed field will never expire. For example:
# Special date/time field to base expirations on.
field :expirable_created_at, type: Time
# TTL index on the above field.
index({expirable_created_at: 1}, {expire_after_seconds: 1.week})
# Callback to set `expirable_created_at` only for guest roles.
before_create :set_expire, if: "role == :guest"
def set_expire
self.expirable_created_at = Time.now
return true
end
Problem
Is there a way to set time to live for a document and then it gets destroyed. I want to create guest users that are temporary per session, so after a week the document gets removed automatically.