【发布时间】:2021-01-24 00:51:01
【问题描述】:
当在 MongoDB 中创建文档时,我试图通过 mongoose 设置 TTL,但我的任何尝试都没有运气。我的项目中正在使用最新版本的猫鼬,据我所知,我已经在 SO 和其他地方在线尝试了最常见的答案。
我的架构
const mongoose = require('mongoose');
const jobSchema = new mongoose.Schema(
{
positionTitle: {
type: String,
},
description: {
type: String,
}
});
const Jobs = mongoose.model('job', jobSchema);
module.exports = Jobs;
我已尝试根据this 问题答案添加一个 createdAt 过期时间:
const jobSchema = new mongoose.Schema({
positionTitle: {
type: String,
},
description: {
type: String,
},
createdAt: { type: Date, expires: 3600 },
});
除了这个选项,它也在同一个问题中,通过时间戳自动创建:
const jobSchema = new mongoose.Schema(
{
positionTitle: {
type: String,
},
description: {
type: String,
},
},
{ timestamps: true }
);
尝试以下变体来设置定义了时间戳的索引:jobSchema.index({ createdAt: 1 }, { expires: 86400 });jobSchema.index({ createdAt: 1 }, { expires: '1 day' });jobSchema.index({ createdAt: 1 }, { expireAfterSeconds: 3600 });
无论我尝试哪个选项,在 MongoDB 的 60 秒周期后,当在文档上设置 createdAt 字段时,文档都会被删除。真的很想知道我做错了什么。
【问题讨论】: