Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't make mongoose expires/ttl to work

var mongoose = require('mongoose'), Cache, cache;

mongoose.connect('mongodb://localhost:27017/test');

Cache = mongoose.model('Cache', mongoose.Schema({
  value: {},
  createdAt: {type: Date, expires: 3600}
}));

cache = new Cache({
  createdAt: new Date(),
  value: {foo: 'bar'}
});
cache.save(function(err, obj) {
  console.log(err, obj);
  process.exit();
});

I'm trying to make the cache get removed after certain time. I waited for more than 3 minutes and the document I inserted did not get deleted at all. Have I missed something?

like image 891
Jürgen Paul Avatar asked Oct 02 '22 06:10

Jürgen Paul


2 Answers

A preferred way to do this:

var cacheSchema = mongoose.Schema({
    value: {},
    createdAt: Date
});

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

mongoose.model( "Schema", cacheSchema );

So the index gets defined to deploy when the connection is made and is given the proper creation options.

Probably best practice to separate Schema and model instance definitions. It's generally handy if you wish to reference that schema somewhere else.

Also see the MongoDB documentation on TTL index creation.

But also, date math: 60 seconds X 60 minutes = 3600

like image 113
Neil Lunn Avatar answered Oct 13 '22 11:10

Neil Lunn


Run this command db.yourdb.getIndexes() in your mongo shell and see what indexes have been created. Check here for more information Mongoose expires property not working properly

like image 44
Luke Kroon Avatar answered Oct 13 '22 10:10

Luke Kroon