How to wait for MongoDB connection to be made before creating HTTP server in Node.js?
Connecting your server to is a database a very crucial task in back-end development as the database is the location where the user-provided data will be stored until further action is taken.
If we fail to connect to the database before creating the server, whatever data is being processed by the server will not get stored in the database. So, as a result, the data is inserted by the client-side will not be persisting in nature.
Express is an open-source, minimal, and robust Node.js web framework used to build web applications and APIs (Application Programming Interface).
To run an express server on your computer, make sure Node.js is installed in your system. To check whether Node.js is installed or not type the below command in the terminal:
If it shows the version of Node.js installed in your system, just like the screenshot below move on to the next step.
Project installation and folder structure:
Step 1: Create a separate GFG folder in your system and navigate to this folder using the command prompt.
mkdir GFG & cd GFG
Step 2: Create a package.json file within the folder using the following command:
Step 3: Create an index.js file in the root directory, this is the file that will start the server. Install express and mongoose package using the following command :
npm install express mongoose
Step 4: Create a connect.js file in the root directory, this is file where the code regarding database connection will be written.
Project Structure: It will look like this. Create connect.js and index.js files as shown below.
Server initialization and process of database connection:
If MongoDB is not installed in your local system, follow this link. Create a database named DEMO_DB(name it according to your wise) using the following command:
We will use mongoose in this article which is an ODM(Object Document Mapper) for Node.js. To know more about it, follow this link. Now write down the following code in respective files.
Step to run the application: Stop the server running using (Ctrl+C) command in the terminal, then restart the server using the following command:
Output: Open the browser and type http://localhost:8000 and we will get the following response.
If this is the response we are getting, then the database has been properly connected to the server by it has been created.