How to automatically delete document in MongoDB using Mongoose on some date

Viewed 3506

I want to create a document which automatically gets deleted on specific time using mongoose in NodeJS.

Writing this as a new question since I can find only TTL based solutions, I need expiry time based.

1 Answers

MongoDB supports auto deleting documents. https://docs.mongodb.com/manual/tutorial/expire-data/

In order to use this in Mongoose you need to create an index on the collection using this syntax: MySchema.index( { "expireAt": 1 }, { expireAfterSeconds: 0 } );

You also need to create a field in schema named expireAt and add the time at which you want the document to expire while adding document in the collection.

Related