Below is the command that can be used via the mongo terminal to set an expiry time for collections (a TTL):
db.log.events.ensureIndex( { "status": 1 }, { expireAfterSeconds: 3600 } )
How do I do this from my code in Node.js using mongoose?
TTL (Time-To-Live) indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time. A background thread in MongoDB reads the values in the index and removes expired documents from the collection (usually every minute).
Mongoose timestamps are supported by the schema. Timestamps save the current time of the document created and also when it was updated in form of a Date by turning it true. When set to true, the mongoose creates two fields as follows: createdAt: Date representing when the document was created.
exports = mongoose. model('User',{ id: String, username: String, password: String, email: String, firstName: String, lastName: String }); It will automatically creates new "users" collection.
Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.
In Mongoose, you create a TTL index on a Date
field via the expires
property in the schema definition of that field:
// expire docs 3600 seconds after createdAt new Schema({ createdAt: { type: Date, expires: 3600 }});
Note that:
createdAt
to the current time when creating docs, or add a default
to do it for you as suggested here. { createdAt: { type: Date, expires: 3600, default: Date.now }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With