{"success":true,"name":"let-mongodb-ttl-indexes-expire-data-instead-of-cleanup-jobs","description":"MongoDB data (sessions, logs, tokens) must be deleted after some time","category":"ai-brimind","path":"ai-brimind/let-mongodb-ttl-indexes-expire-data-instead-of-cleanup-jobs/SKILL.md","file":"SKILL.md","content":"---\nname: let-mongodb-ttl-indexes-expire-data-instead-of-cleanup-jobs\ndescription: \"MongoDB data (sessions, logs, tokens) must be deleted after some time\"\n---\n\n# Let MongoDB TTL Indexes Expire Data Instead of Cleanup Jobs\n\n## When to use\nProject uses MongoDB, and you are about to write cron/cleanup code that deletes old documents by age.\n\n## Example request\nCron job deleting expired sessions nightly → a TTL index on the expiry date field does it automatically, no job to maintain. Password-reset tokens valid 15 minutes → expireAfterSeconds: 0 on an expiresAt field deletes each doc at its own timestamp. Logs kept 30 days → TTL index with expireAfterSeconds = 30 days on createdAt; the database owns retention. Needing exact-second deletion → TTL runs about once a minute; if precision matters, filter expired docs in queries too. Each maps to 'expiration is a built-in index feature, not application code'.\n\n## Instructions\nAct as a developer who checks for a built-in before writing any scheduled cleanup against MongoDB. When documents must disappear after a time: (1) name the retention rule precisely (fixed age from creation? per-document expiry timestamp?), (2) map it to the TTL built-in: a fixed age uses a TTL index on a date field with expireAfterSeconds = N; per-document expiry uses an expiresAt field with expireAfterSeconds: 0, (3) know the mechanism's honest limits and state them: the TTL monitor runs roughly every 60 seconds, so deletion is near-time, not exact — if the app must never SHOW expired items, also filter them in queries (expiresAt: { $gt: now }), (4) confirm the indexed field is a real Date type, because TTL ignores strings and numbers silently. Write a custom cleanup job only if the rule genuinely cannot be expressed as TTL (complex conditions), and justify it. Only implement once the retention rule maps confirmed to the mechanism, and explain why the database now enforces retention instead of a job someone must remember exists.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1056\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}