saf*_*yeh 10 mongoose mongodb node.js
我期待在特定时间删除文档.
const TestSchema = new Schema({
expire_at: {
type: Date,
},
}, {
timestamps: true,
});
TestSchema.index({expire_at: 1}, {expireAfterSeconds: 0});
Run Code Online (Sandbox Code Playgroud)
POST
const test = new TestSchema(this.request.body);
test.expire_at = test.end_time;
try {
yield test.save();
} catch (error) {
this.status = 409;
this.response.body = error.errors;
return;
}
this.response.body = test;
this.status = 201;
Run Code Online (Sandbox Code Playgroud)
似乎文件在expire_at中指定的时间删除.
我使用的是这种日期格式:2016-07-20T05:01:19.567Z
emi*_*svz 17
这将在两小时内删除文档:
const TestSchema = new Schema({
expire_at: {type: Date, default: Date.now, expires: 7200}
})
//expired in 2 hours
Run Code Online (Sandbox Code Playgroud)
要在特定时间删除MongoDB文档,您可以使用TTL(生存时间).TTL索引是特殊的单字段索引,MongoDB可以使用它在一定时间后自动从集合中删除文档.
所以你需要创建一个TTL索引,如:(mongo shell命令)
db.yourCollecName.createIndex({"expire_at": 1 }, { expireAfterSeconds: 5 } );
Run Code Online (Sandbox Code Playgroud)
或者您可以使用mongoose来创建此索引
TestSchema.createIndex({"expire_at": 1 }, { expireAfterSeconds: 5 } );
Run Code Online (Sandbox Code Playgroud)
然后mongodb每隔60秒检查一次,如果expire_at
日期时间小于当前日期时间,那么此记录将在5秒后删除.
TTL索引不保证在到期时立即删除过期数据.文档到期的时间与MongoDB从数据库中删除文档的时间之间可能存在延迟.
删除过期文档的后台任务每60秒运行一次.结果,文档可能在文档到期和后台任务运行之间的期间保留在集合中.
注意:使用createIndex
而不是index
归档时间: |
|
查看次数: |
5925 次 |
最近记录: |