Created
March 23, 2022 12:18
-
-
Save boly38/2d3ead05b2491924ec97ac4d18a86528 to your computer and use it in GitHub Desktop.
Mongoose expireAt example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
suggested PR : Automattic/mongoose#11557