在MongoDB中设置TTL
一开始
MongoDBで追加したRecordにTTLを設定したい場合には、expireAfterSecondsのOptionでIndexを作ってあげると良いのですが、nodeからmongoを操作する時に(一部ハマったのと)ずばり参考になるCodeが無かったので、ご参考までにCodeをチラシの裏しておきます。
-
nodeからMongoDBへのアクセスは、mongodbを使っています(mongooseでは無いです)
node上でSchedule jobを動かすのにnode-scheduleを使っています。npm install node-schedule –save-devとかで入れておいて下さい
节点示例代码
Sample codeのnodeの処理内容は、以下の2つです。1分毎にmongoに追加されるRecordのTTLは90秒なので、2分後には消えている事が確認できます。
-
mongoのRecordに90秒のTTLを持つ様に設定する
nodeのschedule jobで、mongoに対して1分毎に新しいRecordを1件追加と過去の5件のRecordを表示を行う
補充內容
-
coffeescriptで書いています、javascript版はjavascript/coffee converterとかで変換してください
dbName, collectionName, mongoURLはお使いの環境に合わせて下さい
expireAfterSeconds: 90で、ttl_dateの日付から90秒経つと、recordが削除される設定をしています
schedule.scheduleJob(‘*/1 * * * *’,で1分毎にjobを走らせています、表記方法はcronと同様です。
jobの内容は、
objectToRegisterというrecordを1分毎にcollectionにincertする
query_date: -1でsortした最新5件のrecordを表示する
微妙にcallback hellしていますが、promise等で適宜refactorして下さい
以下fileをjs変換して、app.js等でschedulejob = require(‘./routes/schedule’)と読み込んであげると、1分毎にjobが走ります
express = require('express')
schedule = require('node-schedule')
mongodb = require('mongodb')
router = express.Router()
dbName = 'DB_Name'
collectionName = 'Collection_Name'
mongoURL = process.env.MONGO_HOST or 'localhost:27017'
mongodb.MongoClient.connect 'mongodb://' + mongoURL + '/' + dbName, (error, database) ->
collection = database.collection(collectionName)
collection.createIndex { 'ttl_date': 1 }, { expireAfterSeconds: 90 }, (error, items) ->
if error
console.log error
## execute job every 1 minutes
j = schedule.scheduleJob('*/1 * * * *', ->
mongodb.MongoClient.connect 'mongodb://' + mongoURL + '/' + dbName, (error, database) ->
collection = database.collection(collectionName)
dateString = getDateString(new Date)
objectToRegister = {"query_date": dateString, "ttl_date": new Date, "query_key": "hoge" + dateString}
console.log "Incert object : " + JSON.stringify(objectToRegister)
collection.insert objectToRegister, (error, item) ->
if error
console.log error
else
collection.find().sort(query_date: -1).limit(5).toArray (error, items) ->
if error
console.log error
else
console.log "=== Last 5 items ==="
for item in items
console.log JSON.stringify(item)
)
getDateString = (dateInfo) ->
year = String(dateInfo.getFullYear())
month = dateInfo.getMonth() + 1
if (month < 10)
month = '0' + month
day = dateInfo.getDate()
if (day < 10)
day = '0' + day
hour = dateInfo.getHours()
if (hour < 10)
hour = '0' + hour
min = dateInfo.getMinutes()
if (min < 10)
min = '0' + min
return [year, month, day, hour, min].join('-')
module.exports = router