Search code examples
node.jsmongodbmongoose-schema

Delete MongoDB document after some time


I am storing users tokens in a field of user and I want to delete that token after some time nearly equivalent to the expiration time of token so that token automatically gets deleted after some time. I am using schema as:

const userSchema= new mongoose.Schema({
name:{
    type:String,
    default:"a",
    trim:true,
    lowercase:true
},
tokens:[{
    token:{
        type:String,
        expire_at: {
            type: Date, 
            default: Date.now,
            index: { expires: '1m' }
        }
    }
}]
},{
    timestamps:true
})

this method is not working. pls, suggest a way to do that.


Solution

  • What you need is called "TTL Index". But if you want it to be precise, then you will need to have your own mechanism to delete those document; because TTL can not guarantee that such documents are deleted at that instant.

    db.users.createIndex( { "expire_at": 1 }, { expireAfterSeconds: 0 } )
    

    Which will delete documents when the expire_at equals now or beyond.

    Here is the documentation:

    https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time