Search code examples
node.jsmongodbmongooseschemattl

Mongoose TTL for user saved tokens


I have this User schema.

const userSchema = new Schema({
name: {
    type: String,
    required: true,
},
email: {
    type: String,
    required: true,
    unique: true
},
password: {
    type: String,
    required: true
},
tokens: [{
    token: {
        type: String,
        required: true,
    }
}], {timestamps: true});

I would like the token provided will expiresAt given time.

Any suggestions?


Solution

  • That is not possible with mongodb. You can check this document: MongoDb Index TTL

    TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time or at a specific clock time. Data expiration is useful for certain types of information like machine generated event data, logs, and session information that only need to persist in a database for a finite amount of time.

    You can create a new collection for user tokens and relate them on model. I think this could be a better practice. Then you can use ttl index on token collection