LisaAnabel
LisaAnabel

Reputation: 59

Delete Mongoose,Nodejs user at specific time

I have a question.How to delete mongoose and nodejs user at specifific time? Actually, I want the user to be deleted from the database within 60 days after I remove it.How I achieve this?

I have added something like Momentjs, how should it go after this? This code should be deleted after 60 days when the user makes a delete operation.

suspended: true, 
deleted: moment.utc().valueOf()

Upvotes: 2

Views: 1660

Answers (2)

Atishay Jain
Atishay Jain

Reputation: 1445

install any cron package for example https://www.npmjs.com/package/node-schedule and in your mongoose model make sure you're storing the created_at timestamp if not just timestamps:true. running cron everyday

const UserSchema = new Schema({..}, { timestamps: true });

now copy the snippet in your app.js

var schedule = require('node-schedule');

var j = schedule.scheduleJob('0 1 * * *', function(){
  return deleteOldUsers();
});

assuming your model name is User and it's directory is ./models/User

const User = require('./models/User');

deleteOldUsers = () => {
  let current = new Date();
  // subtracting 60 days
  current.setDate(current.getDate() - 60);
  User.deleteMany({ created_at: {$lte: current} }, (err) => {
    if(err) return console.log("Error while erasing users " + err);
    console.log("successfully erased data")
  })
}

EDIT - IF YOU WANT TO USE MOMENT JS INSTEAD OF DATE

const User = require('./models/User');
const moment = require('moment');

deleteOldUsers = () => {
 // subtracting 60 days
 let current = moment().subtract(60, 'days');
 current = moment.utc(current).format();
 User.deleteMany({ created_at: {$lte: current} }, (err) => {
   if(err) return console.log("Error while erasing users " + err);
   console.log("successfully erased data")
 })

}

Upvotes: 2

Akrion
Akrion

Reputation: 18525

You should look into TTL (Time To Live) and partial index:

As of MongoDB 3.2 you could add an expression to the TTL index so that you remove documents only if they match:

db.foo.createIndex({createdDate: 1}, {
    expireAfterSeconds: 5184000, // your 60 days
    partialFilterExpression: {
        // Will remove records which have the `isRemoved` flag equal to true
        isRemoved: true
    }
});

So the idea here is you would flag a user record with isRemoved as true (default would be false) and then this should actually remove it automatically after 60 days.

Upvotes: 0

Related Questions