Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting expiry time for a collection in mongodb using mongoose

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?

like image 224
Amanda G Avatar asked Jan 30 '13 05:01

Amanda G


People also ask

How does TTL work in MongoDB?

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).

What is timestamps in Mongoose schema?

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.

Does Mongoose create collection automatically?

exports = mongoose. model('User',{ id: String, username: String, password: String, email: String, firstName: String, lastName: String }); It will automatically creates new "users" collection.

What does save () do in Mongoose?

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.


1 Answers

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:

  • MongoDB's data expiration task runs once a minute, so an expired doc might persist up to a minute past its expiration.
  • This feature requires MongoDB 2.2 or later.
  • It's up to you to set 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 }}
like image 175
JohnnyHK Avatar answered Sep 19 '22 21:09

JohnnyHK