Jür*_*aul 6 javascript mongoose mongodb node.js
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();
});
Run Code Online (Sandbox Code Playgroud)
我试图让缓存在一定时间后被删除。我等了3分多钟,我插入的文档根本没有被删除。我错过了什么吗?
执行此操作的首选方法:
var cacheSchema = mongoose.Schema({
value: {},
createdAt: Date
});
cacheSchema.index({ createdAt: 1 }, { expireAfterSeconds: 3600 });
mongoose.model( "Schema", cacheSchema );
Run Code Online (Sandbox Code Playgroud)
因此,索引被定义为在建立连接时部署,并给出了正确的创建选项。
Schema可能是分离定义和实例定义的最佳实践model。如果您想在其他地方引用该模式,通常会很方便。
另请参阅有关TTL 索引创建的MongoDB 文档。
而且,日期数学:60 秒 X 60 分钟 = 3600