如何使我的文档自动删除?使用javascript中的Mongoose



我使用猫鼬这是我的模式:

const ShortUrlModel = mongoose.model(
'ShortUrl',
new mongoose.Schema({
original_url: String,
hash: String,
expires_at: { type: Date, expires: 5000 },
}),
);

我把过期在5秒测试,但它不工作

我想10天后到期。

当张贴到我的服务器添加一个url

fastify.post('/new', async (request, reply) => {
let original_url = request.body.url;
let hash = request.body.hash;
const today = new Date();
const expires_at = new Date();
expires_at.setDate(today.getDate() + 10);
let short = await ShortUrlModel.findOne({ hash });
if (short) {
...
} else {
const newShortener = new ShortUrlModel({
original_url,
hash,
expires_at,
});
let saveUrl = await newShortener.save();
console.log(saveUrl);
reply.send({
...
});
}
});

字段为expireAfterSeconds

const ShortUrlModel = mongoose.model(
'ShortUrl',
new mongoose.Schema({
original_url: String,
hash: String,
}, {
expireAfterSeconds: 5000
}),
);

另请注意,如果更改秒数,则需要删除索引并重新创建索引。更改不会仅仅因为更改了架构声明中的秒数而发生。

更多关于更改此处到期

注意2:Mongodb中的文档不会立即过期(例如正好5秒(。这在mongodb文档中有说明。

TTL索引不能保证过期数据在过期后立即删除。文档过期和MongoDB从数据库中删除文档之间可能存在延迟。

最新更新