Andrei Daniel
Andrei Daniel

Reputation: 181

Change variable value in document after some time passes?

I'm quite new to web development and I want to learn new things. I have a mongoose schema (I won't post it because it's in my own language, you won't understand, so I will explain). So I have things like name, a code, what user created the entry, etc. (irrelevant for my problem). I have one variable, let's say, Date like this: type:Date, default: Date.now. There is another one, deactivated: {type: Boolean, default: false}. I want, for each entry, after 4 weeks pass the deactivated variable to change to true.

I have no idea how to do that. I didn't try anything and I searched on Google but I couldn't find anything.

I'd like you to give me the idea and make me understand how I should do it, and then I will try to build it myself.

Upvotes: 0

Views: 715

Answers (2)

Muhand Jumah
Muhand Jumah

Reputation: 1958

What you are asking basically can't be done just like that you have 2 ways about going this route.

  1. Everytime there is an entry retrieval you can run a mongoose hook such as pre('find') that will check if 4 weeks have passed if so then change the deactivated to true you can learn more about hooks on here

Something similar to this example - this example was taken from here

Schema.pre('find', function() {
  if (!this.getQuery().userId) {
    this.error(new Error('Not allowed to query without setting userId'));
  }
});
  1. You can run a cron job every day once or twice (depends on your time period) that keeps checking for records which passed 4 weeks of creation and set deactivated to true

This is a good cron package cron

EDIT: The cron job can be any period, every 10 minutes, 1 hour, 2, 100, etc...

Good luck

Upvotes: 1

mhombach
mhombach

Reputation: 196

Since there are no active "jobs" in mongoose, you cannot change the value in exactly 4 weeks. What you can (and should do) is create a post-find hook (just read the documentation). This enables you to write code that is executed EACH time a find-query has found a document of your schema and your code is executed BEFORE that document is returned to the calling function. This way it would run like this: - you create a user with the now-date - around 5 weeks later the user logs in again - for accessing the user-document, mongoose needs to to a find-query for that document - when the find-query has found the user, your custom hook-code is executed - inside your hook-code you check if the date is more than 4 weeks old - if it is not 4 weeks old, then you do nothing -if it IS 4 or more weeks old, then you change the deactivated to true, save the document and return the saved document (or the first one retrieved). Please read about "hooks" in mongoose, this will definitely help you :)

Upvotes: 1

Related Questions