Change Variable Value In Document After Some Time Passes?
Solution 1:
What you are asking basically can't be done just like that you have 2 ways about going this route.
- 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 totrue
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'));
}
});
- 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
totrue
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
Solution 2:
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 :)
Post a Comment for "Change Variable Value In Document After Some Time Passes?"