I have backend in NodeJS and database is MongoDB. I have a collection for conversations, and each conversation has a field lastResponseMentor and it stores the time when the mentor replied last.
I want to trigger an email using a third party api in my NodeJS backend that if the mentor hasn’t replied within the last 24 hours, an email would be triggered.
How do I keep checking the lastTimeStamp for every mentor in the minimum number of fetches?
lastResponseMentor field in a conversation
Does MongoDB provide some functions or AWS?
2
Answers
There is no build-in function for that, but you can simply query them. I suggest to use a 3rd party date-library, e.g. Luxon, Day.js or Moment.js
Using it natively in MongoDB would be this one:
Note,
$dateSubtract
may not be available in AWS DocumentDB. I did not find any resource whether$$NOW
is available in AWS DocumentDB or not.In fact MongoDB supports it with TTL indexes, database triggers and Atlas functions.
That is you can:
awaiting_for_mentor_reply
, in which you can duplicate the conversation document.lastResponseMentor
for this collection for 24 hours.Mind that this will only work if you’re using Mongo Atlas.
Another way you can workaround it is TTL index and change streams, but it’s not bulletproof.
Another way to do it is using Agenda or similar scheduler.
But the simplest (and hence in my opinion best) solution is periodically fetch conversations with
lastResponseMentor
bigger than 24 hours ago.If you have an index on this field the performance implication is negligible.