Shobhit Tewari
Shobhit Tewari

Reputation: 535

Mongoose document not expiring with expireAfterSeconds

const mongoose = require('mongoose');

const schema = new mongoose.Schema({
    number: {
        type: String,
        required: true,
    },
    otp: {
        type: String,
        required: true,
    },
});

schema.index({createdAt: 1}, {expireAfterSeconds: 30}); //The otp fails to work after 30 seconds

const model = mongoose.model('otp', schema);

module.exports = model;

This OTP document should expire but is not expiring. I tried to recreate the database a few times and look up for possibilities but couldn't find the error.

Upvotes: 0

Views: 463

Answers (2)

alouani_youssef
alouani_youssef

Reputation: 61

you need to have a field with createdAt date type , see in mongodb documentation :

db.log_events.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } );
db.log_events.insert( {
   "createdAt": new Date(),
   "logEvent": 2,
   "logMessage": "Success!"
} )

Upvotes: 0

The background task that removes expired documents runs every 60 seconds.

https://docs.mongodb.com/manual/core/index-ttl/#timing-of-the-delete-operation

The background task that removes expired documents runs every 60 seconds. As a result, documents may remain in a collection during the period between the expiration of the document and the running of the background task.

Because the duration of the removal operation depends on the workload of your mongod instance, expired data may exist for some time beyond the 60 second period between runs of the background task.

The TTL index does not guarantee that expired data will be deleted immediately upon expiration. There may be a delay between the time a document expires and the time that MongoDB removes the document from the database.

Read - http://hassansin.github.io/working-with-mongodb-ttl-index#ttlmonitor-sleep-interval

Upvotes: 2

Related Questions