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)
I believe { timestamps: true } causes autogeneration of a
createdAt
field, not acreatedOn
field. Seems the.index
should referencecreatedAt
. Testing in a project now.