最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can't make mongoose expiresttl to work - Stack Overflow

programmeradmin0浏览0评论
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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

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

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

发布评论

评论列表(0)

  1. 暂无评论