DEV Community

Dezina
Dezina

Posted on

How to delete the document after 30 days of creation using TTL (time to live) index in mongoDB

Just create an index around the createdOn field & give the TTL in seconds. Also add timestamps to true in the schema

Const mongoose = require(‘mongoose’)

Const userSchema = new mongoose.Schema({
{
createdOn: {
type: Date,
required: true
},
.
.
.
}, {timestamps: true})

// delete the document after 30 days of creation. 30 days = 2592000 seconds
userSchema.index({createdOn: 1}, {expireAfterSeconds: 2592000});

module.exports = mongoose.model(‘User’, userSchema)

Discussion (0)