网站搜索

javascript - 无法使 mongoose 的 expires/ttl 工作


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();
});

我正在尝试让缓存在一定时间后被移除。我等了超过三分钟,但我插入的文档根本没有被删除。我是不是漏了什么?

答案#1

一个首选的方法是:

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

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

mongoose.model( "Schema", cacheSchema );

因此,当建立连接时,索引会被定义以部署,并提供适当的创建选项。

最好将 Schema 和 model 实例定义分开。如果你希望在其他地方引用该 schema,这通常很方便。

另请参阅 MongoDB 文档中关于 TTL 索引 创建的内容。

但还有,日期运算:60秒 X 60分钟=3600

答案#2

在你的 mongo shell 中运行此命令 db.yourdb.getIndexes() 并查看已创建了哪些索引。有关更多信息,请查看 Mongoose expires 属性无法正常工作