Search code examples
javascriptnode.jsmongodbservernodemon

Server gradually loses connection to MongoDB until it doesn't connect at all


Good Morning and day to all! I hope this makes sense. I was on here last week as I was missing one step to change my app.js file to server.js and got enough help to make it work. I am returning with an new issue that perhaps stem from that one.. Here is what's happening:

I am working on a MEAN app and I've been working as usual typing mongod to have mongoDB running. and i was using npm start because it was advice to me but usually i use nodemon

I've noticed that gradually my server just completely disconnects and I have to manually restart it by typing 'npm start' again. The connection last about 1 minute before it loses it. However now it doesn't connect at all. I think it has something to do with losing connection to MongoDB because I have a console.log for whenever I don't have mongoDB running to remind me.. (and this is the console log that my server spits out)

server.js

require('net').connect(27017, 'locahost').on('error', function(){
console.log("He's name is MongoDB live from port 27017");
 process.exit(0);

});

I tried switching back to running it with nodemon while it gives me the impression that it's connected as it doesn't spit out any errors when I update any part of my code or refresh the page, it just spits out the console.log message that I showed above and I have to exit and restart..with npm run devel I have no luck either. (this is not happening in other applications)

Here is a look at my command line with all 3 attempts to connect to the server and notice how it spits out the console.log message.. I refresh my page and it doesn't connect at all anymore. It used to! as I mentioned before but for a minute or so. I hope someone can help me out and point me in the right direction.

using npm start, npm run devel and nodemon

my terminal starting server

Package.JSON file

enter image description here


Solution

  • So a friend actually pointed something out to me in my server.js code. I don't recall why but the line that reads process.exit(0); is what's causing mongodDB to lose connection with the server. We removed that it and voila! works like a charm. )no idea how that got there.