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.