I have a working user registration system in NodeJS using Express and Mongoose. At the moment when the user creates an account, a confirmation email will be sent to that email and when the link is clicked, it will confirm their account and let them set a password. Though I want to delete the entire mongo document if the user does not confirm their account within 60 minutes. What is the best method on going about this?
Well mongoose
is a javascript
wrapper over mongoDB
so you should just use regular javascript
to do this.
I would take advantage of the pre
hook:
https://mongoosejs.com/docs/middleware.html#pre
I would set a timeout of 60 minutes and run a delete
query to mongoose
and set the timer id you get in response of the setTimeout
function to the actual document that gets created.
I would then, in case of validation of the account, clear the timer and remove the entry in the new user's document.
In case nothing happens, the document gets programmatically deleted.
schema.pre("save", async function(next) {
const id = setTimeout(function() {
const document = await Model.findOne(/* use some unique value with this */);
await document.remove()
}, 3600000);
this.timerId = id;
next();
}
Then in case of validation you run:
const document = await Model.findOne(/* find the document */);
clearTimeout(document.id);
This should be enough to handle the whole flow.
Please let me know if it's enough! :)