Shobhit Tewari
Shobhit Tewari

Reputation: 535

Document not expiring in mongodb using mongoose

I am storing my refresh tokens in mongodb database. For testing purposes I want them to expire in 4 minutes. For some reason, this thing is not working for me.

const mongoose =  require('mongoose');

let schema = new mongoose.Schema({
    token: {
        type: String,
        required: true
    },
    username: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
});

schema.index({expireAt: 1}, {expiresAfterSeconds: 240}); //4 mins * 60 seconds

let model =  mongoose.model('refresh_token', schema);

module.exports = model;

This is the complete code of my file. I am using this to create the refresh tokens. The item is persisting for an hour as of now. Please shed some light on my mistake.

Upvotes: 0

Views: 1004

Answers (2)

Shobhit Tewari
Shobhit Tewari

Reputation: 535

OK, I solved the issue and it was a blunder from my side.

If you are using mongoose and doing the testing, you would most likely be changing the TTL expire time. I was changing it to see if it was working and for different testing purposes but once the document is created in the atlas, requesting a different TTL time won't overwrite the previous one. I changed the time from 30 months to 5 minutes and did a lot of fluctuation for testing purposes.

So keep this in mind that once the model is created, the TTL will be locked and you need to delete the collection and re-build it otherwise you have to change the TTL settings manually in the atlas(I didn't checked this out because my problem was solved with this only and I was in testing mode of my application). Also

thanks to wak786

for proposing to see the documentation again. It clicked when I was reading how indexing works.

My final refresh token file looks like this after I deleted the collection(actually renamed it).

const mongoose =  require('mongoose');

let schema = new mongoose.Schema({
    token: {
        type: String,
        required: true
    },
    username: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    createdAt: {
        type: Date,
        default: new Date()
    }
});

schema.index({"createdAt": 1}, {expireAfterSeconds: 2592000}); //30days * 24hours * 60 minutes * 60 seconds

let model =  mongoose.model('token', schema);

module.exports = model;

Upvotes: 2

wak786
wak786

Reputation: 1625

You are trying create index using following command.

schema.index({expireAt: 1}, {expiresAfterSeconds: 240});

But the field expireAt does not exist in your schema. And as per the mongo docs :-

If a document does not contain the indexed field, the document will not expire.

Reference:- https://docs.mongodb.com/manual/core/index-ttl/

Upvotes: 0

Related Questions