0

I have created_at date, duration by minutes set by admin and expires_at properties, I have written a logic to calculate the expires_at property and its working fine, also I need to set expired as a boolean to set to true if now date is greater than expires_at I have written a function and its working but I don't know if mongoose can trigger it or when?

so the question is how can I update expired property to true when current time is passed the expires_at time ?

const PollSchema = new mongoose.Schema({
  question: {
    type: String,
    required: true,
  },
  options: {
    type: Array,
    required: true,
  },
  expires_at: {
    type: Date,
  },
  expired: {
    type: Boolean,  
    default: false // how I can update this value to true when now > expires_at;
  },
  duration: {
    type: Number,
    required: true,
  },
});

PollSchema.pre('save', function (next) {
  const poll = this;
  poll.expired = expired(poll);
  next();
});
PollSchema.pre('save', function (next) {
  const poll = this;
  var now = new Date();
  poll.expires_at = now.setMinutes(now.getMinutes() + poll.duration);
  next();
});

// I am triggering this function on save, but I think it should be triggered when now > poll.expires_at;
  
PollSchema.pre('save', function (next) {
  const poll = this;
  const now = new Date();
  poll.expired = now > poll.expires_at;
  next();
});
Yusuf
  • 2,295
  • 7
  • 15
  • 34
  • What is your question? using the pre middleware for save, the code will run for the document when it's created or updated – Paulo Fernando Dec 14 '22 at 16:18
  • Hi, the question is how can I update `expired` property to `true` when current time is passed the `expires_at` time ? – Yusuf Dec 14 '22 at 17:04
  • You want it to be done automatically ritght? Not only when the document is updated right? You will have to use some external stuff to do that, cron jobs for example – Paulo Fernando Dec 14 '22 at 18:07
  • sorry, I should have mentioned that I don't want to make any scheduler or logic on the controller side! – Yusuf Dec 14 '22 at 18:54
  • Hmmm i see, there is not way to automatically update records in mongodb without an external scheduler (unless using cron expressions in Atlas), take a loot at this: https://stackoverflow.com/questions/36291654/event-scheduler-cronjob-in-mongodb – Paulo Fernando Dec 14 '22 at 19:06

0 Answers0