Reputation: 15037
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?
Upvotes: 6
Views: 6618
Reputation: 1113
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
Upvotes: 1
Reputation: 151220
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
Upvotes: 6