1

I have a requirement where i only need to keep all the data that are not older than 7 days. All the data older that should be auto deleted from the database. I want to do this in NodeJs in ExpressJs server.

I have read that i can use setInterval() function for this.

function intervalFunc() {
    //send DELETE request to delete rows older than 7 days.
}
setInterval(intervalFunc,604800000); //interval of 7 days

I want to know how do i write the Delete request to delete only those records that are older than 7 days. And, if there's a better a way to do this??

balexandre
  • 73,608
  • 45
  • 233
  • 342
Zeeshan
  • 55
  • 2
  • 11
  • in your host/machine can you use cron jobs? or a scheduler component? if Yes, it's easier to setup and run every day at mid-night for example, to run that delete script... I've done that, it's a bit more advanced, but boils to that trick – balexandre Feb 17 '20 at 11:28
  • I don't know anything about this. How can I use it with Nodejs? can you share any resources? @balexandre – Zeeshan Feb 17 '20 at 11:35
  • let's [continue here](https://chat.stackoverflow.com/rooms/207976/so60261448) – balexandre Feb 17 '20 at 11:38
  • you have everything in the chat @Zeeshan you can write in the chat as well ... it's a StackOverflow page, for when we want to know a bit more info on a question, or talk about anything :) - you do need to have 20 reputation points to write though :( ... now you do :P – balexandre Feb 17 '20 at 12:06

1 Answers1

0

You can schedule a cron job at the application level to delete the old records. But you can also use "Auto expire documents feature with MongoDB" this feature is since MongoDB version 2.2. MongoDB uses TTL collection for this. TTL collections make it possible to store data in MongoDB and have the MongoDB automatically removing data after a specified number of seconds or at a specific clock time. Read more here :

https://docs.mongodb.com/manual/core/index-ttl/

http://hassansin.github.io/working-with-mongodb-ttl-index

Using Cron job you will have more control over the process such as sending some sort of notification or perform some action once expired data is deleted.

Sandeep Patel
  • 4,815
  • 3
  • 21
  • 37