royhowie
royhowie

Reputation: 11171

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

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?

Upvotes: 4

Views: 5348

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

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

Upvotes: 7

Related Questions