Beginner LevelMongoDB & Mongoose
How do TTL (Time-To-Live) Indexes automatically delete expired documents?
❓ Interview Prompt: Explain TTL (Time-To-Live) Indexes, expireAfterSeconds setting, background expiration threads, and auto-deleting stale sessions/tokens.
TTL (Time-To-Live) Indexes are single-field indexes that MongoDB uses to automatically delete documents after a specified number of seconds or at a target clock time:
Common Use Cases:
•
Automatically purging expired user sessions, OTP tokens, password reset links, and ephemeral cache documents.
Code Implementation Example
typescript
import { Schema, model } from 'mongoose';
const sessionSchema = new Schema({
userId: String,
token: String,
createdAt: { type: Date, default: Date.now }
});
// Automatically delete session documents 3600 seconds (1 hour) after createdAt!
sessionSchema.index({ createdAt: 1 }, { expireAfterSeconds: 3600 });
export const SessionModel = model('Session', sessionSchema);💡Configuring a TTL index to auto-delete documents after 1 hour.
🎯 Interview Key Takeaway
Use TTL indexes to automate purging ephemeral documents like session tokens and OTPs without manual cron jobs.
#TTL Index#Expiration#Automatic Cleanup#Beginner
Back to all MongoDB & Mongoose Questions→