How can I set the TTL date on document creation in Mongoose?

不羁的心 提交于 2021-01-04 07:35:08

问题


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.

This is my promoCode.js file:

var mongoose = require("mongoose");
var promoCodeSchema = mongoose.Schema({
    expirationDate: Date,
    createdAt: {
        type: Date,
        expireAfterSeconds: Number,
        default: Date.now
    }
})
module.exports = mongoose.model("Promo", promoCodeSchema);

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");
    });
})

This doesn't work. I also need to be able to get the value of TTL. How would I go about solving this?


回答1:


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.

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
    }
});

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).



来源:https://stackoverflow.com/questions/24275117/how-can-i-set-the-ttl-date-on-document-creation-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!