Reputation: 3438
We are using express and mongoose, we are trying to remove the document every 1000 seconds in the background, but MongoDB removes at an unexpected time. how to solve it?. also would like to know the difference between expires
and expireAfterSeconds
.
MongoDB - v3.6.5, mongoose - 5.4.3, express - 4.16.4
Sample Model :
const mongoose = require('mongoose');
mongoose.set('useCreateIndex', true);
const forgotPassword = mongoose.Schema({
email: { type: String, required: [true, 'Email field is required']},
expiresAt: { type: Date, expires: '2m', default: Date.now }
}, { timestamps: true, versionKey: false, strict: false });
forgotPassword.index({ expiresAt: 1 }, { expireAfterSeconds : 1000 });
module.exports = mongoose.model('forgotpassword', forgotPassword);
Upvotes: 0
Views: 1299
Reputation: 37048
Both expires and expireAfterSeconds uses TTL index:
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.
Your documents are expected to be removed between 2 and 3 min.
UPDATE:
Check if the collection has correct indexes. Mongoose do not update indexes if the collection already have it.
If expiration time was 0 when you first created the index the documents will be removed within a minute whatever changes you do in your js code until you drop the index, collection, or the whole database.
Use syncIndexes to update indexes on the database side, but be careful to ensure it doesn't happen often on production. It may be quite expensive on large collections.
Upvotes: 1