MongoDB TTL Link to heading
In Mongo, “time to live” is a collection feature which allows docs to be automatically removed in the background.
TTL is implemented through indexes
.
Given a collection with a date type property,
we create an index including the expireAfterSeconds
property:
db.collection.createIndex({
"createdAt": 1
}, {
expireAfterSeconds: 30
})
If createdAt
is present in the document, mongod
will automatically remove the document at createdAt + 30s
.
Mongoose Link to heading
In Mongoose this can be done in the schema creation:
const sessionSchema = new mongoose.Schema({
userId: String,
createdAt: {type: Date, expires: 30}
})