Home > Software design >  Auto Delete MongoDB documents after 30d
Auto Delete MongoDB documents after 30d

Time:08-31

I building a calendar app with React & Express.js & Mongo DB the calendar has month view displays weekly events, and i want to delete these events automaticlly after 30 days

my schema.ts:

import { Calendar } from "../types";

const calendarSchema = new mongoose.Schema<Calendar>(
  {
    startDate: {
      type: String,
      required: true,
    },
    endDate: {
      type: String,
      required: true,
    },
    rRule: {
      type: String,
    },
    title: {
      type: String,
      required: true,
    },
    notes: {
      type: String,
      // required: true,
    },
    type: {
      type: String,
      required: true,
    },
    expireAt: {
      type: Number,
    },
  },
  {
    timestamps: true,
  }
);

calendarSchema.index({ expireAt: 1 }, { expireAfterSeconds: 70 });

export default mongoose.model<Calendar>("Calendar", calendarSchema);

and i am creating a "expireAt" field in my front-end like:

const payload = await createAppointment({
      ...appointment,
      expireAt: new Date().getTime()   80,
    });

now this deletes documents in 40 - 50 seconds, my question is how can i make it 30 or 31 days ? thanks in advance .

CodePudding user response:

The issue is that you set expiry to be after 70 seconds:

calendarSchema.index({ expireAt: 1 }, { expireAfterSeconds: 70 });

Instead of 70 in the expireAfterSeconds just push the value you want, for example for 7 days:

60 * 60 * 24 * 7 = 604800

CodePudding user response:

Change expireAt to Date instead of number

And when creating an index assign 0 to expireAfterSeconds

calendarSchema.index({ expireAt: 1 }, { expireAfterSeconds: 0 });

Now you can define the exact date of when each Calendar will expire, from yearly or down back to seconds

For more info, check MongoDB's documentation

  • Related