1

So i have two collections.

  1. active_posts collection

  2. archived_posts collection

I would like to know if there is a npm module or a mongo feature that will let an active post move to the archived collection when it lived (or was published) for say 20 days.

My post schema is this (temporary):

var postSchema = new Schema({
  title: {type:String},
  created_time: {type: Date, default: Date.now},
  archived: {type: Boolean, default:false}
});

1 Answers1

1

There is no time triggers in MongoDB to do this action by default.

Here are a few workarounds:

1. Background Service Archiving

You can use a scheduler to run repeatedly (let's say every 5 minutes) and checks for documents in the active_posts collection which have passed their TTL, then transfers them to your archived_posts collection.

Read the following Stack Overflow post to find some scheduling libraries for Node.js:
Is there a job scheduler library for node.js?

Here are some libraries to name a few: node-cron, node-schedule, Agenda, ...

2. Scheduled (Delayed) Archiving

You can schedule the archiving job for each document at the time of creation.

In addition to libraries mentioned above, you can use Kue which has an option for scheduling a job to be done once in a certain time.


TIP: MongoDB has a built-In functionality to delete documents after they pass their TTL, you may find it useful in conjunction with these methods. But use with caution!
You can read about it in the official documentation, and in the following Stack Overflow post:
Delete MongoDB document at specific time

Kayvan Mazaheri
  • 2,447
  • 25
  • 40
  • Thanks for your response. However, i found some modules like ol-mongoose-ttl that does what i want, but it works on the whole document, just like the built-in feature of MongoDB. What i want is to work on single entries or rows in a document. I can't seem to find any. A scheduler seems a bit complicated to me. – Naoufal EL BANTLI Aug 14 '17 at 09:30
  • 1
    @NaoufalELBANTLI If you find anything that suits your requirements, consider posting it as an answer here for future reference. – Kayvan Mazaheri Aug 14 '17 at 10:25