skip to Main Content

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


  1. 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

    const { DateTime } = require("luxon");
    db.collection.find({
       lastResponseMentor: { $lt: DateTime.now().minus({ hours: 24 }).toJSDate() },
    })
    

    Using it natively in MongoDB would be this one:

    db.collection.find(
       {
          $expr: {
             $lt: [
                "$lastResponseMentor",
                { $dateSubtract: { startDate: "$$NOW", unit: 24, amount: "hour" } }
             ]
          }
       }
    )
    

    Note, $dateSubtract may not be available in AWS DocumentDB. I did not find any resource whether $$NOW is available in AWS DocumentDB or not.

    Login or Signup to reply.
  2. In fact MongoDB supports it with TTL indexes, database triggers and Atlas functions.
    That is you can:

    • create an auxiliary collection awaiting_for_mentor_reply, in which you can duplicate the conversation document.
    • add TTL index for lastResponseMentor for this collection for 24 hours.
    • add Atlas function that reacts for deletes in this collection and runs some business logic (sends email or sends request to your API that will send an email)
      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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search