如何在 Mongoose 中设置文档创建的 TTL 日期? [英] How can I set the TTL date on document creation in Mongoose?
问题描述
我正在尝试在 Mongoose 中创建一个 promoCode
架构.在创建时,我需要能够设置促销代码的到期日期.促销代码不一定具有相同的 TTL
.我看了这个问题,但我的文档仍未过期.
I am trying to make a promoCode
schema in Mongoose. On creation, I need to be able to set the promo code's expiration date. Promo codes do not necessarily have the same TTL
. I looked at this question, but my documents still aren't expiring.
这是我的 promoCode.js
文件:
var mongoose = require("mongoose");
var promoCodeSchema = mongoose.Schema({
expirationDate: Date,
createdAt: {
type: Date,
expireAfterSeconds: Number,
default: Date.now
}
})
module.exports = mongoose.model("Promo", promoCodeSchema);
现在,在 routes.js
中,我有:
Now, in routes.js
, I have:
app.post("/admin/promo/create", isLoggedIn, isVerified, isAdmin, function (req, res) {
var promo = new Promo();
promo.createdAt.expireAfterSeconds = 60;
// for reference, note the actual day on which the promo code should expire
var days = parseInt(req.body.expiration.replace(/[^\d]+/g, "")) || 1;
promo.expirationDate = new Date(Date.now() + (days * 24 * 3600 * 1000));
promo.save(function (err) {
console.log(err, promo);
return res.redirect("/admin/promo");
});
})
这不起作用.我还需要能够获得 TTL
的值.我将如何解决这个问题?
This doesn't work. I also need to be able to get the value of TTL
. How would I go about solving this?
推荐答案
当您想为每个文档使用不同的 TTL 值时,您可以在包含过期时间戳(如此处所述),然后设置该时间戳以反映您对每个文档所需的 TTL.
When you want to use different TTL values for each doc, you can use an expires
time of 0 on a field that contains the expiration timestamp (as described here) and then set that timestamp to reflect your desired TTL for each doc.
您已经在架构中计算了 expirationDate
,因此您希望将 TTL 索引放在该字段上,而不是 createdDate
.但是您需要在定义中使用 expires
,而不是像您使用的那样使用 expiresAtSeconds
:
You're already computing expirationDate
in your schema, so you'd want to put your TTL index on that field instead of createdDate
. But you need to use expires
in the definition, not expiresAtSeconds
like you're using:
var promoCodeSchema = mongoose.Schema({
expirationDate: {
type: Date,
expires: 0
},
createdAt: {
type: Date,
default: Date.now
}
});
然后在 routes.js
中,您只需将新 Promo
文档上的 expirationDate
设置为其到期时间戳(就像您在已经在做).
And then in routes.js
you only need to set expirationDate
on the new Promo
docs to its expiration timestamp (like you're already doing).
这篇关于如何在 Mongoose 中设置文档创建的 TTL 日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!