mehraeen mozhdi
mehraeen mozhdi

Reputation: 19

how to delete a record of a collection after a specific amount of time

i want to create an OTP (one time password) for my node js application using mongodb as database after generating otp and sending that for client with email i want to store the otp as hashedOTP in database and delete (or expire) that after a specific amount of time like 2 minutes but iam having some problem with that and i dont know how to do it i have read some articles and mongodb documentations about TTL but i didn't understand that how its working at all and i guess its just about date type records so i did it with js setTimeout method and in small scales its working fine but because iam not experienced i dont know that it work fine with biger scales or not here is my schema that i made and i tried expires and expiresAfterSeconds for hashedOTP but it didnt worked

const adminSchema = new mongoose.Schema({
firstName : {
    type : 'string'
},
lastName : {
    type : 'string'
},
email : {
    type : 'string'
},
password : {
    type : 'string'
},
phoneNumber : {
    type : 'string'
},
role : {
    type : 'string'
},
confirmationToken : {
    type : 'string'
},
hasConfirmedEmail : {
    type : Boolean,
    default : false
},
hashedOTP : {
    type : 'string',
}

})

now the first question is saving OTP in database is correct way? here is my code for handling with setTimeout

    try {
    const hashedotp = await bcrypt.hash(otp,10)
    verifiedAdmin.hashedOTP = hashedotp
    await verifiedAdmin.save()
    setTimeout(async () => {
        console.log('set time out gonna work now ')
        verifiedAdmin.hashedOTP = ''
        await verifiedAdmin.save()
    }, 120000);

i know that it is not necessary to hash the otp but i just did it and the verifiedAdmi is the user that i want to send otp for it and its made by above schema i just feel that this setTimeout is not going to work fine cause it has many interactions with database

Upvotes: 0

Views: 712

Answers (2)

Amit Shaw
Amit Shaw

Reputation: 1

Instead of deleting you do do the below:

Create a different model let say , OtpVerification with fields userId (indexed, because lot of searching will be done), otp (the random number) and expiresAt (current time + 10 minutes can be done easily using moment js).

Then while verifying find in OTPVerification if any document with that userId present if present check otp and

if (expiresAt > currentTime) {
   // allow 
} else {
   // otp expired
}

Upvotes: 0

Akash NO
Akash NO

Reputation: 316

If you want to delete the hashedOTP after a fixedTime (ie 120000 second) , You could run a cron job and update the collection by checking against the createdAt time

1 - Run Cron Job

2 - if( time of checking is greater than createdAt + 120000 sec) then delete the hashotp

const CronJob = require('cron').CronJob;

 new CronJob({
    cronTime: "00 */5 * * * *", //every five minutes
    onTick: function() {
       helperFunctionToUpdateData()         
    },
}), 

i prefer using moment.js to check time difference

Upvotes: 1

Related Questions