Skip to content

Instantly share code, notes, and snippets.

@boly38
Created March 23, 2022 12:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boly38/2d3ead05b2491924ec97ac4d18a86528 to your computer and use it in GitHub Desktop.
Save boly38/2d3ead05b2491924ec97ac4d18a86528 to your computer and use it in GitHub Desktop.
Mongoose expireAt example
import mongoose from 'mongoose';
const { Schema } = mongoose;
const Listing = new Schema({
"listing_id": { type: Number, index: true, unique: true },
"title": String,
"expireAt": { type: Date, expires: 10 } // <========== TTL index here
});
export { Listing };
/**
* Details:
**********
* This mongo schema sample will create a specific behavior for the field "expireAt" (of "listings" collection)
* when "expireAt" field is set, then the listing entry become expired after "expiredAt" date value + N seconds (in this example N=10)
**
* mongooose creates related mongo TTL index : db.listings.getIndexes()
(...)
{
"v" : 2,
"key" : {
"expireAt" : 1
},
"name" : "expireAt_1",
"background" : true,
"expireAfterSeconds" : 10
}
**
* Instant of deletion: please keep in mind that an expired entry doesn't mean that the entry will be removed immediately.
* Mongo TTL index is well documented, and the background job that remove deprecated entries may arrive some seconds later, cf. link.
**
* Mongoose expires doc (may be improved) : https://mongoosejs.com/docs/api.html#schemadateoptions_SchemaDateOptions-expires
* Mongodb ttl index : https://docs.mongodb.com/manual/core/index-ttl/#timing-of-the-delete-operation
**/
@boly38
Copy link
Author

boly38 commented Mar 23, 2022

suggested PR : Automattic/mongoose#11557

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment