How to set different expiry times for different documents in Mongoose

Viewed 13

So far in all the code samples I have seen on how to create self destructing documents in Mongodb the expireAt field is usually always constant as shown below

new TokenSchema({token:String, type:String, createdAt: { type: Date, expires: 3600 }});

Is there no way to make this expires field value computed dynamically? Such that I can have:

let newToken = new Token({
   token,
   type,
   expires: getTimeToDestroy() //Computed programmatically
});
newToken.save();

The reason been that I don't want all tokens to expire after 3600s, I want some to expire after a programmatically computed amount of seconds depending on the token type.

Thanks

1 Answers

Yes, you can do that. Set expires: 0 and put the desired date into that field. I am not familiar with mongoose, could be like this:

new TokenSchema({token:String, type:String, destroyAt: { type: Date, expires: 0 }});

See Expire Documents at a Specific Clock Time

Related