skip to Main Content

Good evenings, sirs. I wonder how can i delete records in Sequelize after certain time passes? For example, I want to delete unauthorized records after 10 days.I am new to Sequelize so if you can give me an idea, i will be very thankful.

2

Answers


  1. I think below code will help you to achieve this. Here the example is showing to delete data after 24 hours. Hope this will help you.

    const { Op } = require('sequelize');
    
    await ExampleTable.destroy({
        where: {
            createdAt: {[Op.lte]: new Date(Date.now() - (60*60*24*1000))}
        }
    });
    
    Login or Signup to reply.
  2. I think this code will not run automatically unless you run that manually, So, You should have to use cron job, it will run your code every time you specified

    Here, An example of how can you start a cron job.

    // Importing required libraries

    const cron = require("node-cron");
    const express = require("express");
    app = express(); // Initializing app
    

    // Creating a cron job that runs every 10-second

    https://crontab.guru/ // where you can check cron time

    cron.schedule("*/10 * * * * *", function() {
         console.log("running a task every 10 second");
         // write your login here, delete your records
    });
    app.listen(3000);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search