Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose conditional TTL for document

Is there any way to set expiresAt index only for some documents, depending on current document state?

like image 520
BadVolt Avatar asked Nov 21 '25 01:11

BadVolt


1 Answers

Yes, there is. You need to set both partialFilterExpression and expiresAt indexes. Works only at mongodb 3.2+

Code below will remove document after 24h only if paid property is equal to false:

let billingSchema = new mongoose.Schema({
_id:type:Number,
summ:{
    type:Number,
    required:true
},
description:String,
paid:{
    type:Boolean,
    default:false,
    index:true
},
ownerId:{
    type:mongoose.Schema.Types.ObjectId,
    ref:'User',
    index:true
}
},{timestamps: true,_id: false});
billingSchema.index({createdAt: 1},{expireAfterSeconds: 24*60*60,partialFilterExpression : {paid: false}});
like image 83
BadVolt Avatar answered Nov 22 '25 15:11

BadVolt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!