Reputation: 36319
Looked over the MongoDB and Mongoose docs and can't see if this is even possible. I'll tell you up front I've written no code attempting to do this yet, because I can't find anything to hook into for it.
What I'm looking for is after setting a TTL expiry on a MongoDB document (inserted via Mongoose in case that matters), I'd like the application to get a notification when the document is ejected from the collection. Is there a way to do that native to MongoDB, or will I have to do something on my own (e.g. polling)?
Upvotes: 1
Views: 2938
Reputation: 165
Here's a mongoose plugin that can help you. It implements TTL feature and calls onReap
function each time reaper being executed.
var ttl = require('mongoose-ttl');
var schema = new Schema({..});
schema.plugin(ttl, {
ttl: 'the time each doc should live in the db (default 60 seconds)',
interval: 'how often the expired doc reaper runs (default 5 mins)',
onReap: 'callback passed to reaper execution'
});
Should mention that this plugin does not utilize native MongoDB TTL feature.
Upvotes: 1
Reputation: 65323
There are no server-side hooks for your application to get notified when MongoDB documents are removed via a TTL index.
However, a TTL index is just a date-based index used by a server-side TTL thread that wakes up every minute and deletes new documents matching the expiry criteria.
If you want to add some sort of on-delete hook, I would suggest writing your own expiry script and running this as a scheduled task via cron
or equivalent. This script could first run a query to find matching documents ready to be expired, and then implement whatever notification your application needs before the documents are actually deleted.
Upvotes: 2