0

I have a NodeJS server that has the following Mongoose Schema:

const mongoose = require("mongoose");
const EventSchema = new mongoose.Schema(
    {
        _id: mongoose.Schema.Types.ObjectId,
        type: String,
        time: Date,
        expireAt: { type: Date, expires: 0 }
    },
    { timestamps: true }
);

EventSchema.index({ "expireAt": 1 }, { expireAfterSeconds: 0 })
const Event = mongoose.model('Event', EventSchema);

Event.watch().on('change', data => { //I want only 1 instance of my server to watch this
    let { operationType } = data;
    if (operationType === "delete") {
      //Perform an operation based on deletion only once
    }
});

module.exports = Event;

The server is hosted on heroku. Now, when I scale the number of dynos for the server to 2. All 2 instances of the server are now listening for changes to the document as achieved using the Event.watch function.

How can I make sure that irrespective of how many dynos running in production, only 1 instance can listen for changes made to the document.

Thanks.

ololo
  • 1,326
  • 2
  • 14
  • 47

0 Answers0