Setting expiry time for a collection in mongodb us

2019-01-07 09:57发布

问题:

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?

回答1:

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


回答2:

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


回答3:

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.



回答4:

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