gpt4 book ai didi

javascript - 无法使 mongoose 过期/ttl 工作

转载 作者:可可西里 更新时间:2023-11-01 09:44:39 26 4
gpt4 key购买 nike

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分多钟,我插入的文档根本没有被删除。我错过了什么吗?

最佳答案

执行此操作的首选方法:

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

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

mongoose.model( "Schema", cacheSchema );

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

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

另请参阅 TTL index 上的 MongoDB 文档创作。

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

关于javascript - 无法使 mongoose 过期/ttl 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22470172/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com