Home > Mobile >  Automatically delete documents based on a condition mongoose
Automatically delete documents based on a condition mongoose

Time:11-29

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.

CodePudding user response:

You can try partialFilterExpression.

db.users.createIndex(
  {"createdDate": 1}, 
  {expireAfterSeconds: 300, partialFilterExpression: {verified: false}}
);

CodePudding user response:

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 }
  }
}
  • Related