Am using mongoose-ttl plugin in my mongoose database, my problem is, whenever a record is deleted by ttl and i restart my node server and my server makes a connection to mongodb via mongoose, all records that have ttl index and is not expired yet also gets deleted. Sometimes restarting my server and making connection deletes all records from the collection even if their time is not even near. Worst part is that, even when the time has passed all records dont get deleted untill the last document with TTL Index gets deleted. Please help.
const EventSchema = new Schema({
//
});
EventSchema.plugin(ttl, { ttl: 60000});
//
const event = new Event({
ttl: "2m"
})
You don't have to use mongoose-ttl
in fact if you want behavior you've described you should use mongodb expire mechanism.
Setup for mongoose could be like this:
const EventSchema = new Schema(
{
expiresAt: { type: Date, default: Date.now, expires: 0 },
},
);
EventSchema.virtual('ttl').set(function(ms) {
this.expiresAt = new Date(Date.now() + ms);
});
EventSchema.virtual('ttl').get(function() {
return this.expiresAt - Date.now();
});
const event = new Event({
ttl: 2 * 60 * 1000, // expire time in milliseconds
});
If you have fixed expire time, just don't worry about ttl
setter and getter and set expires: desired_expire_time_in_ms