What is the best way to terminate a MongoDB client connection in the event of an error?

I am currently managing a configuration where I have set up a MongoDB instance and operating two JavaScript services on a Linux server. One of the services, moscaService.js, is responsible for listening to MQTT topics on the server and storing the incoming data in a MongoDB collection. The second service, integrationService.js, runs periodically scanning the same MongoDB collection for new entries and sending them to Ubidots if any are found.

The issue arises when both services attempt to operate simultaneously through the same IP/port combination - localhost:27017. In cases where one service is actively working and the other attempts to establish a connection, it results in a connection error, forcing a restart of the service.

Below are the connection components of each service:

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://127.0.0.1:27017/myGateway';


//integrationService.js
var job1 = new CronJob('*/1 * * * * *', function() {
  MongoClient.connect(url, function(err, db) {
      if(err != null) {
          logger.error({message: 'Connection error: ' + err});
          process.exit(0);
      } else {
          executeService();
      }

      function executeService() {
        // execution block
      }
  });
}, null, true, timeZone);


//moscaService.js
server.on('published', function(packet, client) {

  //the packet is read here

  MongoClient.connect(url, function(err, db) {
      if(err != null) {
          logger.error({message: 'Connection error: ' + err});
          process.exit(0);
      } else {
          executeService();
      }

      function executeService() {
        // execution block
      }
  });
});

To address this challenge, I seek a solution that effectively manages the err without abruptly terminating the service. If the service reboots while new messages are being published, they risk getting lost. Perhaps implementing a check to ensure the port is open before making a connection or utilizing an alternative port could be considered.

An initial attempt was made to create a separate MongoDB instance on a different port so that each service could listen on its own designated port. However, it appeared that MongoDB restricts multiple instances from connecting to the same database.

The excerpts provided above offer a glimpse into the situation at hand. Should additional details be required for further assistance, please feel free to mention it, and I will gladly supply the necessary information.

Answer №1

I successfully resolved the issue by modifying the code. I adjusted the code so that the integrationService establishes a connection to MongoDB before initiating the CronJob. This ensures that it only connects once and maintains the connection throughout.

Below is the modified section of the code for establishing the connection:

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://127.0.0.1:27017/myGateway';

//integrationService.js
MongoClient.connect(url, function(err, db) {
  var job1 = new CronJob('*/1 * * * * *', function() {
    if(err != null) {
        logger.error({message: 'Connection error: ' + err});
        process.exit(0);
    } else {
        executeService();
    }

    function executeService() {
      // execution block
    }
  }, null, true, timeZone); // end CronJob
}); // end MongoClient.connect

As this adjustment effectively resolved the issue, I have retained the treatment of err as it was originally (although a more sophisticated approach would be preferable).

The problem has been resolved in both the integrationService and the moscaService, but I intend to apply the same modification to the latter service as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JQuery jqx validation is experiencing some issues

Utilizing jquery plugins and widgets from jqx for basic form validation in my ruby-on-rails application has proven to be very helpful. Here is a simple example of an HTML form: <form id="newForm"> <input type="text" id="name"/> < ...

Adding a new object to a mongoDB collection using its unique id

I have a collection named Users where user messages and information are stored. My goal is to add new objects to the existing collection based on their id. When trying to perform this action, I encounter an error 'TypeError: user.insert is not a func ...

Change the text of a button by using an input field

How can I dynamically update button text based on input field value? <input class="paymentinput w-input" type="tel" placeholder="0" id="amount-field"> <button id="rzp-button1" class="paynowbutton w-button">Pay Now</button> I want the bu ...

Trouble arises when managing click events within the Material UI Menu component

I've implemented the Menu Component from Material UI as shown below - <Menu open={open} id={id} onClose={handleClose} onClick={handleClick} anchorEl={anchorEl} transformOrigin={{ horizontal: transformOriginRight, vertical: t ...

The React form is only transmitting a single property from the state instead of the complete state

My current challenge involves sending form data from my react client to my nodejs server. The issue I am facing is that only the last property of the state gets sent to the server upon form submission. This problem seems to be occurring on the client side, ...

What is the process for creating instant notifications using AJAX, PHP, and MySQL?

I am looking to implement real-time notifications on my website and have already set up the notification bar: <div class="alert alert-info alert-with-icon" data-notify="container"> <button type="button" aria-hidden="true" class="close"> ...

Using PHP to calculate the total number of records within an HTML document

I am currently working on a PHP script to establish a connection with my MySQL database in order to retrieve the total number of users registered on my forum by counting the records in the table. The PHP script should display the total count above the sec ...

When a previous form field is filled, validate the next 3 form fields on keyup using jQuery

Upon form submission, if the formfield propBacklink has a value, the validation of fields X, Y, and Z must occur. These fields are always validated, regardless of their values, as they are readonly. An Ajax call will determine whether the validation is tru ...

Expanding your JavaScript skills: Tackling nested object key and value replacements

I am looking to manipulate the values of a nested object using JavaScript. The structure of the object is outlined below. let jsonObj = { "service":[ { "name":"restservice", "device&quo ...

Utilizing React JS to neatly display Firebase data in a table

Before I post, I always make sure to do my due diligence by searching on Google, YouTube, forums, or trying to figure it out on my own. I even check questions similar to mine asked by other people, but unfortunately, I'm stuck. Currently, I am using ...

The automated Login Pop Up button appears on its own and does not immediately redirect to the login form

Hey guys, I'm struggling with modifying the jquery and html to ensure that when the login button is clicked, the login form pops up instead of displaying another login button. Another issue I am facing is that the login button seems to pop up automati ...

Having trouble including a YouTube iframe code within the document ready function

I am having trouble getting the youtube iframe API code to work properly within my $(document).ready() function. When I try to add the code inside the function, the player does not load. However, when I move the code outside of the document.ready, the play ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...

How can Vue be used to dynamically change the input type on focus?

What Vue method do you recommend for changing an input element's type on focus? e.g. onfocus="this.type = 'date'" I am specifically looking to switch the input type from text to date in order to utilize the placeholder property. ...

Displaying random characters in place of Angular 6 font awesome icons

Recently, I started a new project with the angular cli and incorporated font-awesome 4.7.0. After that, I included it as a dependency in my angular.json file. "styles": [ "./node_modules/font-awesome/css/font-awesome.min.css", "./node ...

Start Vue.js development server with SSL enabled (for secure HTTPS serving)

Issue with Development Environment: Recently, I encountered an obstacle related to enforcing HTTPS on external hosts as explained in "Deprecating Powerful Features on Insecure Origins". This problem arose because I have my development setup on my laptop an ...

What are the steps to effectively utilize data retrieved from readFragment using Apollo?

Once a user logs in, the system returns a jwt token and a user object containing the id and firstName, which are then stored in cache (refer to the image link provided below). https://i.stack.imgur.com/oSXZ5.png I aim to retrieve the user information fro ...

Create a form with Vue that generates input fields based on JSON data and

I am seeking assistance with implementing a truncate filter for vueformulate in my project. I am generating the form from json data and need to limit the label to 80 characters, with a read more/less option. The data is dynamic, so changing the label in th ...

Filtering data by query in Node.js Express is a helpful feature that

I have a query that needs to filter data based on the ID I pass. However, it's currently showing all data instead of filtering by the specific ID. This is how I am trying to find the data: router.get('/getannouncementsbyrestaurant/:id', asy ...

Steps to partially open the Modal Sheet Swipe Step by default

I've set up a modal sheet component with the following structure: <f7-sheet class="myClass" style="height: auto" swipe-to-step :backdrop="false" > <div class="sheet- ...