I am looking into deleting a document at a specific time.
const TestSchema = new Schema({
expire_at: {
type: Date,
},
}, {
timestamps: true,
});
TestSche
To delete MongoDB document in specific time you can use TTL (time to live). TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time.
So you need to create a TTL index like: (mongo shell command)
db.yourCollecName.createIndex({"expire_at": 1 }, { expireAfterSeconds: 5 } );
or you can use mongoose to create this index
TestSchema.createIndex({"expire_at": 1 }, { expireAfterSeconds: 5 } );
then mongodb check after every 60 second and if expire_at
date time is less than the current date time then this record will remove after 5 second.
The TTL index does not guarantee that expired data will be deleted immediately upon expiration. There may be a delay between the time a document expires and the time that MongoDB removes the document from the database.
The background task that removes expired documents runs every 60 seconds. As a result, documents may remain in a collection during the period between the expiration of the document and the running of the background task.
TTL Indexes
NB: Use createIndex
instead of index