1
const notificationSchema = mongoose.Schema({
    type:{
        type: String
    },

    message:{
       type: String
    },
    userId:{
        type: String,
        required: true,

    },
    timestamp:{
        type: Date,
        default: new Date()

    },
    expireAt: {
        type: Date,
        default: Date.now,
        index: { expires: '5m' },
      },
})

My data is not getting automatically delete in mongoose, Is something wrong with my model? Here is my Structure of model.Can anyone help

2 Answers2

2
const notificationSchema = mongoose.Schema({
type:{
    type: String
},

message:{
   type: String
},
userId:{
    type: String,
    required: true,
},
{ 
  timestamps: true
}
});

notificationSchema.index({createdAt: 1},{expireAfterSeconds: 3600});

Each field in the collection will be deleted after 3600seconds

kedar sedai
  • 1,687
  • 3
  • 16
  • 25
0

There's several ways, but one that pops to mind is TTL.

"TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time or at a specific clock time."

Find out more here > https://docs.mongodb.com/manual/core/index-ttl/

And for mongoose > https://github.com/mongoosejs/mongoose-ttl

Leafyshark
  • 395
  • 2
  • 5
  • 11