Trouble Connecting Local Server to MongoDB Despite Configuring Network Access

I am currently working on a project where I need to connect to a MongoDB instance from two different servers: one is a Heroku server and the other is my local development server.

I have successfully set up my Heroku server to connect and interact with MongoDB without any issues. However, I am having trouble establishing a similar connection from my local server.

I am unsure why this is happening as I’m not manually terminating the process and there doesn’t seem to be any unhandled exceptions causing the process to crash.

Has anyone faced a similar issue or have any insights on what could be causing this disconnection? Any help in troubleshooting this would be greatly appreciated.

Thank you in advance for your help.

const mongoose = require("mongoose");

mongoose.set("strictQuery", true);

const isDev = process.env.NODE_ENV !== "production";
const dbURI = process.env.MONGODB_URI;

mongoose.connect(dbURI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

mongoose.connection.on("connected", () => {
  console.log("MongoDB connection established!");
});

mongoose.connection.on("error", (error) => {
  console.error(`MongoDB connection error: ${error}`);
  process.exit(-1);
});

//New Unhandled exceptions method
mongoose.connection.on("disconnected", (error) => {
  if (error) {
    console.error(`MongoDB connection disconnected: ${error}`);
    process.exit(-1);
  } else {
    console.log(error);
    process.exit(0);
  }
});

// Handle SIGINT event for graceful shutdown
process.on("SIGINT", (err) => {
  if (err) {
    console.error(err);
  }
  connection.close(() => {
    console.log("MongoDB connection closed due to app termination");
    process.exit(0);
  });
});

`// Load the required packages
const express = require("express");
const nodemon = require("nodemon");
const dotenv = require("dotenv");
const cors = require("cors");

// Load the environment variables from the .env file
dotenv.config();

// Initial database connection
const db = require("./data/db");

// Import routes
const linkButtonRoute = require("./routes/linkButtonRoute");

// Create an express app
const app = express();

app.set("view engine", "ejs");

// Use the express.json() middleware to parse incoming request bodies
app.use(express.json());

app.use(cors());

// Set the port for the application
const port = process.env.PORT || 5000;

// Mount the routes to the express app
app.use("/api/linkButton", linkButtonRoute);


// Start the server
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});