Change variable value in document after some time passes?

后端 未结 2 1753
伪装坚强ぢ
伪装坚强ぢ 2021-01-26 09:45

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 e

相关标签:
2条回答
  • 2021-01-26 10:23

    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 :)

    0 讨论(0)
  • 2021-01-26 10:24

    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

    0 讨论(0)
提交回复
热议问题