You can expire documents after a time (or at a specified time), but AFAIK you can’t expire a collection.
You first need to set an index on the collection. From your example, I would do:
Meteor.startup(() => {
test._ensureIndex({ creationDate:1 }, { expireAfterSeconds:30 });
// or you could use:
// test.rawCollection().createIndex({ creationDate:1, expireAfterSeconds:30 });
});
Then, you would change your method’s insert:
test.insert({
_id: test_id,
creationDate: new Date()
});
That’s really all there is to it.
However, the expiration timestamp is only checked by the MongoDB engine every minute, so it’s unlikely that your document will be deleted exactly when you want it to be.
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.
Because the duration of the removal operation depends on the workload of your mongod instance, expired data may exist for some time beyond the 60 second period between runs of the background task.
I did like you told me, it’s not working the document is still here,
Let me explain to you a bit more, as soon as i do my POST request on my NodeJs server i want the meteor to add it ( that’s working ) but the collection is still here even after 30 seconds .
However, the expiration timestamp is only checked by the MongoDB engine every minute, so it’s unlikely that your document will be deleted exactly when you want it to be.
The comment below is taken from that MongoDB manual page:
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.
Because the duration of the removal operation depends on the workload of your mongod instance, expired data may exist for some time beyond the 60 second period between runs of the background task.
Having said that, 190s is quite a long way from 30s (or even 30s+60s). My tests rarely have deletions more than 60s late, and usually better than that.
You should maybe try dropping the index and letting it get re-created because once created, you can’t change your mind about the value in expireAfterSeconds*. This will fix a situation where you may have initially created the index with a higher expireAfterSeconds.