Connecting Node Express App to MongoDB
1) Firstly, we will create a post object, so we will go to our js file. In this file’s post function, we extract the post data and show it on the console log. Now, we will store that data to the database instead of showing it into the console. So, we will import our mongoose model in the following way:
2) Now we will use the postmodel constant in our posts route to create a new post based on our body data. We will use the postmodel constant in the following way:
3) Now, we have a post object that is managed by the mongoose. We will now connect our node express app to MongoDB, and for that, we will go to the MongoDB cluster. Here, we will click on the CONNECT, and when we click on it, we will see the following screen:
4) We will click on the Connect your application from this page, and this click will give us a connection string. We will copy it from here and go back to our app.js file.
5) In the app.js file, we will import the mongoose and use the connect function of it after creating the express app in the following way:
6) In this connect function, we will pass the string which we have copied from the cluster as a string in the following way:
One thing is to be noted here, and that is, we need to replace the password here (we have stored the password in our previous section). So, we will replace it in the following way:
7) We will connect a method here, i.e., then. This function will output something, if everything is working. We will also use the catch() function to catch any potential errors. We will use both of these function in the following way:
We successfully get connected to the database. Now, in the next section, we will learn how to store data into a database.