【问题标题】:Can't make mongoose expires/ttl to work不能让猫鼬过期/ttl 工作
【发布时间】:2014-04-23 14:11:25
【问题描述】:
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();
});

我正在尝试在特定时间后删除缓存。我等了 3 多分钟,我插入的文档根本没有被删除。我错过了什么吗?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    在您的 mongo shell 中运行此命令 db.yourdb.getIndexes() 并查看已创建的索引。在这里查看更多信息Mongoose expires property not working properly

    【讨论】:

      【解决方案2】:

      这样做的首选方法:

      var cacheSchema = mongoose.Schema({
          value: {},
          createdAt: Date
      });
      
      cacheSchema.index({ createdAt: 1 }, { expireAfterSeconds: 3600 });
      
      mongoose.model( "Schema", cacheSchema );
      

      因此,index 被定义为在建立连接时进行部署,并提供适当的创建选项。

      分离Schema 和model 实例定义可能是最佳实践。如果您希望在其他地方引用该架构,这通常会很方便。

      另请参阅有关 TTL index 创建的 MongoDB 文档。

      还有,日期数学:60 秒 X 60 分钟 = 3600

      【讨论】:

        猜你喜欢
        • 2020-12-01
        • 2022-01-05
        • 2017-01-05
        • 2018-07-22
        • 2015-04-01
        • 2018-05-02
        • 2017-05-26
        • 2013-02-13
        • 1970-01-01
        相关资源
        最近更新 更多