有没有一种方法可以设置文档生存时间,然后销毁它。我想创建每个 session 都是临时的 guest 用户,因此一周后该文档将自动删除。
最佳答案
MongoDB(2.2及更高版本)实际上具有特殊的索引类型,该索引类型使您可以在文档上指定TTL(请参阅http://docs.mongodb.org/manual/tutorial/expire-data/)。数据库将为您删除过期的文档-无需执行cron作业或任何其他操作。
Mongoid支持此功能,如下所示:
index({created_at: 1}, {expire_after_seconds: 1.week})
created_at
字段必须包含日期/时间信息。在模型中包括Mongoid::Timestamps
可免费获得。更新:
如果只想使文档的一个子集过期,则可以创建一个仅为该子集填充的特殊日期/时间字段。在索引字段中没有值或没有日期/时间值的文档将永远不会过期。例如:
# 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
关于ruby-on-rails - Mongoid文件的生存时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14685271/