Skip to content
Advertisement

How to Wait Until a MongoDB Connection is Made before Using the Database

I have the following code to create a connection to my MongoDB database, and to store it for future use.

JavaScript

My problem is that _database is undefined until the connection is made. If my website tries to use the database before _database is defined it will throw an error and crash.

I want to make it so instead of crashing, other portions of my code would just wait until _database is not undefined. Sounds like a await/async solution is needed, but I can’t wrap my head around how to approach implementing something like that here. Any advice would be great!

Advertisement

Answer

First approach: To make mongoConnect an async function and await on it before any of the remaining code is executed.

JavaScript

In the beginning of your code

JavaScript

Second approach: To make getDb function await till database connection is available

JavaScript

Sample code for you to run and check the second approach:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement