The Heroku app is having trouble communicating with the Mongo Atlas database, leading to frequent crashes

My deployed application on Heroku was working fine until I encountered an issue with the connection to my MongoDB Atlas database. Despite my attempts to resolve it, the application keeps crashing. The Heroku logs show the following:

"2022-12-05T10:19:21.000000+00:00 app[api]: Build succeeded
2022-12-05T10:19:24.577606+00:00 heroku[web.1]: Starting process with command `npm start`
2022-12-05T10:19:26.144610+00:00 app[web.1]: 
2022-12-05T10:19:26.144634+00:00 app[web.1]: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b07021f1f070e0f092b5a455b455b">[email protected]</a> start
2022-12-05T10:19:26.144634+00:00 app[web.1]: > node index.js
2022-12-05T10:19:26.144635+00:00 app[web.1]: 
2022-12-05T10:19:26.369713+00:00 app[web.1]: Running on port: 36914
2022-12-05T10:19:26.725509+00:00 heroku[web.1]: State changed from starting to up
2022-12-05T10:19:56.365761+00:00 app[web.1]: Connected successfully to db server
2022-12-05T10:19:56.367567+00:00 app[web.1]: /app/node_modules/mongodb/lib/utils.js:698
2022-12-05T10:19:56.367568+00:00 app[web.1]:           throw error;
2022-12-05T10:19:56.367569+00:00 app[web.1]:           ^
2022-12-05T10:19:56.367569+00:00 app[web.1]: 
2022-12-05T10:19:56.367571+00:00 app[web.1]: TypeError: Cannot read properties of undefined (reading 'db')
2022-12-05T10:19:56.367571+00:00 app[web.1]:     at /app/dal.js:10:17
2022-12-05T10:19:56.367572+00:00 app[web.1]:     at /app/node_modules/mongodb/lib/utils.js:695:9
2022-12-05T10:19:56.367572+00:00 app[web.1]:     at /app/node_modules/mongodb/lib/mongo_client.js:285:23
2022-12-05T10:19:56.367573+00:00 app[web.1]:     at connectCallback (/app/node_modules/mongodb/lib/op...

package.json

{
  "name": "littledb",
  "version": "1.0.0",
  "description": "lowdb sample for 1.125",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "jest"
  },
  "author": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afcecdcac3efc2c6db81cacbda">[email protected]</a>",
  "license": "MIT",
  "dependencies": {
    "cors": "^2.8.4",
    "express": "^4.16.3",
    "http-server": "^14.1.1",
    "lowdb": "^1.0.0",
    "mongodb": "^3.7.3",
    "nodemon": "^2.0.20"
  },
  "devDependencies": {
    "@types/mongodb": "^4.0.7"
  }
}

dal.js

const MongoClient = require('mongodb').MongoClient;
const url         = 'mongodb://localhost:27017';
let db            = null;
 
// connect to mongo
MongoClient.connect(url, {useUnifiedTopology: true}, function(err, client) {
  
    db = client.db('baddestbank');
});

// create user account
function create(name, email, password){
    return new Promise((resolve, reject) => {    
        const collection = db.collection('users');
        
    })
}

// find user account
...

I have followed the instructions to resolve the issue with '@types/mongodb' in my VS Code but I'm still facing problems.

Despite having correct config vars on Heroku and MongoDB Atlas, my application is failing to sync data from the frontend to the MongoDB database. I have reviewed the IP address settings on Atlas as well.

The application functions correctly locally, but the deployment is causing the crashes. I have a deadline for my MIT project in 3 days, so I need to find a solution soon.

GitHub repository

The expected behavior was for the app to connect successfully to the database and allow users to access their accounts, but currently, it is failing to push data and authenticate users.

Answer №1

Connecting to deployed databases can present challenges when hardcoded references are in place. Here are some helpful suggestions:

1 - Utilize environment variables or configuration specific to local development and production environments

  • Install dotenv npm i dotenv
  • Create an .env file in the root directory of your project
  • Add a line like this to the .env file -
    DB_URI='mongodb://localhost:27017'
  • At the beginning of index.js or dal.js, include require('dotenv').config()
  • Avoid hardcoding the url in dal.js, instead use const url = process.env.DB_URI
  • In your Heroku configuration, set the DB_URI value for your production deployment. Refer to Heroku documentation

Why? Making changes to the DB url or other configurations within the code can be cumbersome. By adding variables to your environment in platforms like Heroku and your local machine, no code changes are necessary, resulting in a more robust system.

2 - Ensure your web server (or other critical tasks) only starts once the database connection is established

Create a function in dal.js that connects to the database and confirm that it is connected before allowing it to proceed

function connectToDB () {
  return new Promise((resolve) => {
    const url = process.env.DB_URI
    MongoClient.connect(url, { useUnifiedTopology: true }, function (err, client) {
      if (err) console.error(err)
      console.log('Connected successfully to db server')
      db = client.db('myproject')
      resolve()
    })
  })
}

Invoke this function before starting your web server, for example, at the end of index.js, implement the following:

const init = async () => {
  await dal.connectToDB()
  const port = process.env.PORT || 3000
  app.listen(port)
  console.log('Running on port: ' + port)
}
init()

Why? It's essential to wait for a confirmed connection before indicating readiness to process. While there may be exceptions, this remains a fundamental best practice.

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

Utilizing numerous instances of setInterval

I've created a jsFiddle which can be found here: http://jsfiddle.net/dztGA/22/ Main Objective: My aim is to have two independent timers on the same page that can be stopped and restarted either by hovering or manually. The Issue: The problem illustr ...

How can tick values be displayed on a c3js line chart when all data is unselected?

I'm currently working with a c3js line chart that displays 3 different lines. However, I noticed that when I remove all data sources, the x-axis tick values disappear. Is there a way to keep the x-axis tick values visible even when there is no data pr ...

The CORS policy specified in next.config.js does not appear to be taking effect for the API request

I am currently working on a Next.js application with the following structure: . ├── next.config.js └── src / └── app/ ├── page.tsx └── getYoutubeTranscript/ └── getYoutubeTranscript.tsx T ...

CSS Toggle failing to show updated styles

Initially, I successfully changed the font and color of text on Google using a simple code. However, when I attempted to incorporate it into a toggle on / off switch, the changes did not take effect. To address this issue, I sought assistance from ChatGPT ...

Refreshing the page results in a 304 status update

I am currently working on a music playlist/blog website project using React, Node/Express, and PostgreSQL. The website is hosted on Heroku, and you can access the live app here: Live app: When a user clicks on the “Earth Nights #1” card on the homepa ...

I possess a certain input and am seeking a new and distinct output

I am looking to insert a word into an <input> and see an altered output. For example, Input = Michael Output = From Michael Jordan function modifyOutput() { var inputWord = document.getElementById("inputField").value; var outputText = "print ...

Unable to retrieve the .attr() from a button that was created using handlebars

I am currently working on developing a web scraper as part of a homework task that involves using Express, Mongoose, Cheerio/axios, and Handlebars. In my "/" route, I retrieve the Mongoose objects and use Handlebars to display them on the page in individua ...

Update the browser URL dynamically without redirecting the page, by utilizing JavaScript after an AJAX call receives a

I am currently endeavoring to find a solution to replace the URL on my page without triggering a reload. My approach involves utilizing an infinite scroll JavaScript plugin. Upon receiving a response from an AJAX call, I intend to update the URL with the n ...

React Component - Element with an undefined value

When I tried implementing an Ionic Modal as a React Component, I encountered the following error message: Type '({ onClose, tipo }: PropsWithChildren<{ onClose: any; tipo: number; }>) => Element | undefined' is not assignable to type & ...

The interaction between a JavaScript function call and C# is not functioning properly

Attempting to invoke the JavaScript function from CodeBehind ( C# ) : function scrollToBottom() { window.scrollTo(0, document.body.scrollHeight); } The function successfully executes when directly called from my asp.net application. However, ...

Extracting data from CSV files, transforming it into JSON format, and then saving it in

As I work on processing a CSV file in Pandas, my goal is to convert each row into a JSON object, append them to a dictionary, and then store them in MongoDB. Below is the code snippet: data = pd.DataFrame(pd.read_csv('data/airports_test.csv')) ...

Tips on querying MongoDB with a list of values

Can anyone help me with a MongoDB query for the following document? I need to find all documents that contain the GUID 360DC2AE-2B67-4E8D-E320-71D0D30D90F7, regardless of whether it is in the 1st node or any node within the contactlists.values. The query ...

Evaluating the conditional rendering of a React child component using Jest and Enzyme

I am currently working on expanding the test coverage for this particular file: import React, { useContext } from 'react'; import UserContext from '../../contexts/user'; import styles from './index-styles.scss'; const UserLog ...

Modifying the background image of div elements with JQuery in a loop function is ineffective when using Google Chrome

I am facing an issue in my application where I have a for loop to change the background image of two divs. The code snippet is as follows: for (var i = 0; i < length; i++) { $("div_" + (i + 1)).css("background-image", "../imageFile.png"); ...

Make sure to allow the async task to complete before beginning with Angular JS

As I develop an app using MobileFirst v8 and Ionic v1.3.1, I encounter issues with timing in my code execution. Specifically, when the application initiates, the regular ionic angular code within my app.js file runs. This section of the code handles the i ...

The flat function for JavaScript Arrays is not defined in React Native

I am currently developing an application using react-native and it's common knowledge that we can utilize JavaScript code in this particular project as well as any other react projects. However, whenever I attempt to use the following code snippet, t ...

Using Node.js, express, jade, highcharts, and a 2D array

Greetings, I am relatively new to the realm of javascript/node.js/express/jade/highcharts etc... The predicament at hand is as follows: I have a template that takes in a few parameters which are pre-processed in my router code. These parameters are group ...

perform an action in PHP when a button is clicked

I'm currently developing a PHP admin panel that displays a list of users in an HTML table format. Each row in the table includes a button that allows the admin to send a notification to the selected user. Below is the code I used to create and displa ...

What is the best way to showcase 100 json data entries within an HTML document?

Starting from scratch with html, css, and javascript, I've embarked on a basic learning project. Within this project, I plan to create two main pages: a list page and a detail page. The list page will showcase posts on the html screen, featuring only ...

How come these functions continue to be executed asynchronously even when the Async module is being utilized?

My decision to utilize the Async module aimed at populating a mongodb collection according to a specific order proved to be quite challenging. Despite the fact that the code worked without Async, it failed to insert documents in the desired sequence: func ...