mongodbmongoosettldatabase-indexes

Automatically delete documents based on a condition mongoose


I have a database with users collection which contains a verified field in its schema. I want users that have not been verified 5min after account creation to be deleted. How can I do this?

I am already familiar with the expires option, but I am not sure how I can apply it conditionally.


Solution

  • You can create a field expireAt with an index and use expireAfterSeconds and partialFilterExpression options:

    ...
    verified: { type: Boolean, default: false },
    expireAt: {
      type: Date,
      default: Date.now,
      index: {
        expireAfterSeconds: 300,
        partialFilterExpression: { verified: false }
      }
    }