0

I'm stuck with setting TTL on object field or nested document.

I have 'Product' and 'Promotion' collection and 'Product' collection has 'onPromotion' field which type is Object like below:

Promotion = {
    promotionName: String,
    ...,
    expires: Date.now() + (24 * 60 * 60 * 1000)
}

Product = {
    productName: String,
    ...,
    ...,
    onPromotion: {
        expires: Date.now() + (24 * 60 * 60 * 1000), // after a day
        promotionId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Promotion'
        }
    }
}

The promotion detailed data is stored in Promotion collection, and Product references it, and I want mongoDb to remove the promotion field automatically. For that, I made an index for 'Promotion' Collection like below:

Promotion.createIndex({ expires: 1 }, { expiresAfterSecond: 0 });

But I don't know how to set TTL for the field in Product collection. Maybe I'm thinking of SQL's 'on delete cascade' option.

I referenced this article: MongoDb TTL on nested document is possible? and there's no way to set ttl on a field, but a document.

So I'm stuck how to solve this. Any help can be appreciated!

Community
  • 1
  • 1
jolacaleb
  • 69
  • 2
  • 7

0 Answers0