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?
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?
Share Improve this question edited Jun 26, 2017 at 11:18 Neil Lunn 151k36 gold badges355 silver badges325 bronze badges asked Mar 18, 2014 at 4:07 Jürgen PaulJürgen Paul 15k28 gold badges96 silver badges136 bronze badges2 Answers
Reset to default 6A 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
Run this mand 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