Setting expiry time for a collection in mongodb using mongoose

node.jsMongodbMongoose

node.js Problem Overview


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?

node.js Solutions


Solution 1 - node.js

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 }}

Solution 2 - node.js

this code is working for me.

may it help

let currentSchema = mongoose.Schema({
    id: String,
    name: String,
    packageId: Number,
    age: Number
}, {timestamps: true});

currentSchema.index({createdAt: 1},{expireAfterSeconds: 3600});

Solution 3 - node.js

Providing a string to expires also works nicely with Mongoose if you do not want to deal with the expire time calculation and improve the overall readability of the schema.

For example here we are setting the expires to 2m (2 minutes) and mongoose would convert to 120 seconds for us:

var TestSchema = new mongoose.Schema({
  name: String,
  createdAt: { type: Date, expires: '2m', default: Date.now }
});

Mongoose would create an index in the background and auto set the expireAfterSeconds to in this case 120 seconds (specified by the 2m).

It is important to note that the TTL process runs once every 60 seconds so it is not perfectly on time always.

Solution 4 - node.js

If you are working with Mongodb Atlas Replica Sets - try:

import * as mongoose from 'mongoose'; 

let currentSchema = new mongoose.Schema({
        createdAt: { type: Date, expires: 10000, default: Date.now },
        id: String,
        name: String,
        packageId: Number,
        age: Number
        });

currentSchema.index({"lastModifiedDate": 1 },{ expireAfterSeconds: 10000 });

Solution 5 - node.js

There is a npm library - 'mongoose-ttl'.:

var schema = new Schema({..});
schema.plugin(ttl, { ttl: 5000 });

you can see all the options of this library: https://www.npmjs.com/package/mongoose-ttl

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmanda GView Question on Stackoverflow
Solution 1 - node.jsJohnnyHKView Answer on Stackoverflow
Solution 2 - node.jsSadegh TeimoriView Answer on Stackoverflow
Solution 3 - node.jsAkrionView Answer on Stackoverflow
Solution 4 - node.jsJason MullingsView Answer on Stackoverflow
Solution 5 - node.jsarrView Answer on Stackoverflow