Osama Ahmaro
Osama Ahmaro

Reputation: 143

How can i switch TTL index on and off using mongoose?

I want to create a user account on my app, and have that user deleted after a certian amount of time if this user hasn't confirmed his account, and switch TTL off if the user has confirmed his account.

Here is my Schema:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  }
  ,
  isConfirmed: {
    type: Boolean
  },
  code: {
    type: String
  },
  createdAt: {
    type: Date,
    expires: 3600,
    default: Date.now
  }
})

module.exports = User = mongoose.model('users', UserSchema)

Upvotes: 0

Views: 401

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

Since you have already added TTL index on createdAt field, you can easily turn it off by deleting the createdAt field on successful account confirmation.

If a document has createdAt value and it is older than the specified time, then it will be deleted. But, if you delete that field on account confirmation, it wont be deleted. Thus you need to delete createdAt field on account confirmation.

If you want to keep createdAt field, you can add TTL index on some temporary field like expireAfter and delete it on account confirmation.

  expireAfter: {
    type: Date,
    expires: 3600,
    default: Date.now
  }

After account confirmation.

User.findOneAndUpdate({_id : user_id},{$unset : {expireAfter:1}})

From official docs :

MongoDB will automatically delete documents from the collection when the document’s createdAt value is older than the number of seconds specified in expireAfterSeconds (in your case expires ).

For more information read MongoDB TTL index docs

Upvotes: 2

Related Questions