DEV Community

Dezina
Dezina

Posted on

4

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)

Top comments (1)

Collapse
 
bdwellons profile image
Brant Wellons

I believe { timestamps: true } causes autogeneration of a createdAt field, not a createdOn field. Seems the .index should reference createdAt. Testing in a project now.