Home » Connecting Node Express app to MongoDB in MEAN Stack

Connecting Node Express app to MongoDB in MEAN Stack

by Online Tutorials Library

Connecting Node Express App to MongoDB

In our previous section, we learned how to create a mongoose model. We will now use that mongoose model to create JavaScript objects that allow us to do one magic trick. We will also learn how to connect our node express to our mongodb. For using the mongoose model, we will create a post object and use the following steps:

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:

Connecting Node Express App to MongoDB

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:

We passed a JavaScript object in the above code, where we defined the data needed for our schema.

Connecting Node Express App to MongoDB

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:

Connecting Node Express App to MongoDB

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.

Connecting Node Express App to MongoDB

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:

Connecting Node Express App to MongoDB

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:

Connecting Node Express App to MongoDB

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:

Connecting Node Express App to MongoDB

We successfully get connected to the database. Now, in the next section, we will learn how to store data into a database.


You may also like