6
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?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Jürgen Paul
  • 14,299
  • 26
  • 93
  • 133

2 Answers2

6

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

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
1

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

Community
  • 1
  • 1
Luke Kroon
  • 1,016
  • 12
  • 19