Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically update property of mongoose documents (node.js) object after certain time

I am currently developing a node.js server with MongoDB as the database system.

I know, that there is TTL (Time To Live) and "expires" for mongodb to delete documents after a certain time. My Problem is, that I don't want to delete the documents, i just want to set them "inactive".

So, is there something similiar to set a property after a certain time of a document, for example a boolean "isActive" from true to false?

Are there any common MongoDB or node.js approaches to do this?

Thanks!

like image 959
basedgod Avatar asked Nov 25 '14 13:11

basedgod


1 Answers

There are no (time delayed) triggers in MongoDB to automatically trigger an action like this.

The TTL feature simply runs a job every minute that checks the dates (in an index) and determines what should be removed. For your application, you could build something similar.

Add an indexed date field, named for example: inactiveAfter.

Run a job every minute (or some other period, depends on your db size) that updates documents ({$set: {status:"inactive", inactiveAfter: null}}) that will be expired. For performance reasons, make sure that the query only needs to touch the index(es). Don't forget to set {multi: true}.

Scheduling your job can be done in many ways, but a simple cronjob will do the job. I'd put this task in a separate project, apart from your main node server.

like image 138
RickN Avatar answered Oct 20 '22 16:10

RickN