skip to Main Content

In my application I have activity logs of users stored in my DB (mongoDB), Since a lot of logs are collected within 3 months I want to Delete all the activity log records older than 3 months from current date. I using Node.js for my backend. I want to run this function everyday automatically. Please help me with this.

This is the Log model

const logSchema = new mongoose.Schema(
  {
    activityType: {
      type: String,
      require: true,
      enum: {
        values: [
          'create',
          'update',
          'delete',
          'login',
          'logout',
          'passwordReset',
        ],
        message: 'Wrong activity type!',
      },
    },
    activitySubject: {
      type: Object,
      require: true,
    },
    activityPerformedUserId: {
      type: String,
      require: true,
    },
  },
  { timestamps: true }
);

const Log = mongoose.model('log', logSchema);

module.exports = Log;

This is how my activity log document looks like.

{
  "_id": "62788f467a6d842face8a698",
  "activityType": "delete",
  "activitySubject": {
  "id": "627557836752492b6c7ff515",
  "name": "S Thomson",
  "nic": "78456123442"
  },
  "activityPerformedUserId": "6276ab95eb9e634310ea37f8",
  "createdAt": "2022-05-09T03:49:26.510Z",
  "updatedAt": "2022-05-09T03:49:26.510Z"
}

2

Answers


  1. The best feature of MongoDB which deletes the record to granular level precision is TTL

    Create a field on which the entire document will be removed after that time has passed. For ex, if you want to delete a record on x day, y hour, z minute, then set the value of the TTL field to x y z.

    In your case, you can set TTL field to createdAt + 90 days, so that it will remove it after 90 days from createdAt value

    Login or Signup to reply.
  2. Here it would be like

    const a =  {
      "_id": "62788f467a6d842face8a698",
      "activityType": "delete",
      "activitySubject": {
        "id": "627557836752492b6c7ff515",
        "name": "S Thomson",
        "nic": "78456123442"
      },
      "activityPerformedUserId": "6276ab95eb9e634310ea37f8",
      "createdAt": "2022-05-09T03:49:26.510Z",
      "updatedAt": "2022-05-09T03:49:26.510Z"
    }
    

    Try this:

    a.splice(a.findIndex(e => new Date(e.createdAt + 2592000000 ) > new Date()),1);
    console.log(a);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search