0

When I create a new "BlacklistedToken" document, I want it to be automatically deleted from my mongoDB database after lets say 1 day. So exactly 24 hours from after it has been created and added to the database, I want it automatically deleted.

I know there is something called TTL and I have seen examples of expiration dates being set for documents, but I never understood how to implement it with my code below.

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
  token: {type: String, required: true, unique: true}
}, {timestamps: true});

module.exports = mongoose.model("BlacklistedToken", UserSchema);

const newBLT = new BlacklistedToken(
  { token: req.cookies.cookieJWT }
);
await newBLT.save();

Bonus question: What I am blacklisting is a JWT accesstoken. The tokens expires 24 hours after creation, and they are also stored in a httpOnly cookie which also expires in 24 hours. Now when I want to blacklist the token, is it possible to get the remaining time till the cookie expires and use that time as the TTL property when I create the new BlacklistedToken document?

TTL = req.cookies.cookieJWT.timeTilItExpires; // something like that
  • Does this answer your question? https://stackoverflow.com/questions/14597241/setting-expiry-time-for-a-collection-in-mongodb-using-mongoose – JBaczuk Mar 03 '22 at 21:08
  • So all I have to do is type: createdAt: { type: Date, expires: '1d', default: Date.now }? How does that work when I am already using timestamps which creates a createdAt property for me? @JBaczuk –  Mar 03 '22 at 21:19
  • IDK if mongoose will complain or not. Have you tried it? – JBaczuk Mar 03 '22 at 22:08
  • I just removed the timestamps because I figured I dont need them anyways, and it kinda works, but regardless of what value I set where it says expires, it always gets deleted after 1 minute always so I am really comfused now @JBaczuk –  Mar 03 '22 at 23:01
  • maybe some more searching? https://stackoverflow.com/questions/56580063/mongoose-deleting-all-documents-at-every-one-minute-and-not-accepting-time-from – JBaczuk Mar 04 '22 at 00:58

0 Answers0