Deleting a document in monogid after sometime

牧云@^-^@ 提交于 2020-01-17 11:15:34

问题


I am working on rails app with mongoid. This is one of model(collection):

class Document
 include Mongoid::Document
 include Mongoid::Timestamps
 include Mongoid::Paperclip

 field :time, type: Time
 field :radius, type: Float
 attr_accessible :time,:radius
end

The time field contain the actual time when model should be deleted. How can I do that , One idea I have to write a script put that in cron job. But I don't want to create a cron job. Is there any other way I can automate this or any method inside rails model I can define or something inbuilt into rails only. I am surely missing something.


回答1:


You can achieve this without cron by using TTL indexes.

All you need to do is to put a TTL index on that field:

db.log.events.ensureIndex( { "time": 1 }, { expireAfterSeconds: 3600 } ) // this means that it will expire in 1 hour after the time in the field `time`



回答2:


You can use delayed_job gem: https://github.com/collectiveidea/delayed_job

document.delay(run_at: time).destroy



回答3:


Add this line in your model to achieve it:

index({:time => 1}, {background: true, expire_after_seconds: 0})

Also doing the index in the background in case your collection is large. You need an index because to find the items to delete you don't want to have to seek through the whole collection.



来源:https://stackoverflow.com/questions/20088242/deleting-a-document-in-monogid-after-sometime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!