Establish communication between the backend APIs and database
This lecture covers testing POST requests with Postman, structuring API URL patterns by controller, and connecting a Node.js and Express backend to MongoDB with Mongoose.
Getting a Node.js application to return an HTML page is one thing. Getting it to actually receive data from a frontend, route that data to the right controller, and store it in a database is a different problem entirely, and it's the one this lecture works through step by step, from testing requests in Postman to getting a live connection to MongoDB.
Beyond GET: testing other request types with Postman
The previous lecture ended with a basic GET request returning an HTML page in the browser. A backend needs more than GET, though; PUT, POST, DELETE, and PATCH requests all come up regularly, and a browser alone can't easily send them. Changing a route from a GET handler to a POST handler in the code is simple, but testing it needs a dedicated tool: Postman, which can send any of these request types directly. Sending a POST request to a URL that only had a GET handler previously and getting back the expected response is the first confirmation the change worked.
Structuring URL patterns by controller
As an application grows past a single user controller, it picks up a search controller, a product controller, a review controller, and more. To keep requests routed correctly, each one needs a unique API pattern. A pattern like /api/user tells the application to route the request to the user router specifically. Within that router, further action is needed to distinguish between operations like creating, deleting, or updating a user, which is why a route gets an additional segment, like /create, to uniquely identify which controller method handles it.
Avoiding manual restarts with nodemon
Restarting the application by hand after every code change gets old fast. Installing nodemon (npm install nodemon) fixes that: it's added as a dev dependency, since it's only needed during development and not in deployment, and a script entry runs the app through nodemon instead of node directly. Once that's wired up, saving a code change triggers an automatic restart, and the change is reflected without any manual intervention.
Sending real data from frontend to backend
Data moving from a frontend to a backend API travels as a payload, typically in JSON format. In Postman, that means sending raw JSON data in the request body, for example a name, an email, and a password field, for a "create user" request. In a professional environment, a password would be hashed before it's ever sent, though this lecture sends it directly for the sake of demonstrating the basic flow. To actually see what the backend received, logging request.body inside the controller is the way to check, but by default the request body comes back undefined until the application is told what format the incoming data is in. Adding app.use(express.json()) in app.js fixes that, and after that middleware is in place, the same request correctly logs the name, email, and password fields the frontend sent.
Connecting the backend to MongoDB
With the frontend-to-backend communication working, the next step is backend-to-database communication, using MongoDB as the database. Mongoose is the dependency that handles this, playing a role similar to an ORM like Hibernate for a Spring Boot application: it avoids a lot of boilerplate and lets you run queries when you actually need them, following an MVC-style pattern. After installing Mongoose (npm install mongoose), a dedicated db folder with an index.js file inside it requires Mongoose and calls mongoose.connect with the local URI of the database, retrievable from MongoDB Compass by copying its connection string, followed by the specific database name being used.
Handling the connection asynchronously
Connecting to a database is an asynchronous process: the application kicks off the connection and moves on to its next steps without waiting for the connection to finish first. A .then() handler logs a success message once the database actually connects, and a .catch() handler logs an error message if it doesn't. Requiring that db/index.js file from app.js starts the connection process as soon as the application starts, but because it's asynchronous, the "server is running" message can print before the "database connected" message does, which is expected behavior rather than a bug.
Debugging a connection refused error
Running into a "connection refused" error pointing at the MongoDB URI and port often traces back to how localhost resolves on a given machine. Replacing "localhost" in the connection string with the explicit loopback IP address, 127.0.0.1, resolves this in many cases, since it removes any ambiguity about which address the application is actually trying to reach.
Key takeaways
- Postman is the tool for testing POST, PUT, PATCH, and DELETE requests that a browser can't easily send on its own.
- API URL patterns should map to specific controllers (like /api/user), with additional segments identifying the exact action within that controller.
- Nodemon eliminates manual restarts by watching for file changes and restarting the server automatically, and belongs in dev dependencies only.
app.use(express.json())is required for Express to parse an incoming JSON request body; without it,request.bodycomes back undefined.- Mongoose connects a Node.js backend to MongoDB and reduces boilerplate, similar to how an ORM works in other frameworks.
- Database connections are asynchronous, so a "server running" log can appear before a "database connected" log without indicating an error.
- A "connection refused" error against a MongoDB URI can often be resolved by using 127.0.0.1 instead of localhost in the connection string.
Who this is for
This lecture is for developers learning backend fundamentals who have already built a basic Node.js and Express application and are ready to connect it to a real database. It picks up directly from an earlier lecture on routers and controllers, and the next lecture continues by using Mongoose to create a user record in the database.
Full transcript(auto-generated, with timestamps)
[0:03]Hello everyone in our last lecture we basically understood how an NBC project looks and we understood what a router is and what a controller is and then we also understood uh how to create a basic no nodejs application and uh return return the HTML uh return an HTML page and display it in the browser uh so in this lecture what we are going to discuss is about how to communicate from frontend to the backend API and from our API how to communicate with the database so that we can store the data in our backend backend database our backend database here is our mongod DB server
[0:54]This one so just let's let's get started initially during our last lecture we ended over here like where we created a in Local Host uh we it actually basically sends and get respon uh get request uh AP request and actually gets the response from our controller but get is not the only AP request that can be sent that is get there is put there is post there is delete and there is patch and many more so to show show you you that I'm going to actually just change this get AP request into a post AP request in our back end to change that in code nothing
[1:40]Much we need to do just go and change get into post that's it it it is now a post request so if you refresh the application see the we are getting get slash that is the this URL pattern doesn't the slash URL pattern doesn't have a get AP request in our application that is what it is showing because we have changed it to post so to when we have a post API API in our backend system how to test it if we don't uh if we can't access it from browser for that we have a specialized tool called uh Postman inside the postman from Postman you can
[2:31]Actually send various types of API request like get put post patch different types so now I'm we haven't created any URL patterns as such so we'll just use that slash uh sorry and we'll send it as a post request right now and see what response we are getting from the application see we got the H1 create user that was sent from this controller user.js controller H1 if it was in the browser it would have HTML page and it would have shown only the Crea that we saw initially so the next point I wanted to add is uh here we are just showing the create user
[3:24]But as our application progresses we just we are not just going to have only user as user controllers we are going to have search controller we are going to have product controller we are going to have a review controller so there are going to be various types of controllers so to uniquely identify them uh through our API we have an API pattern that we need to follow I'm going to have an API pattern for uh post uh I'm going to create an AP pattern for the user router so user router is specific to uh user related task so if this API pattern occurs that is API
[4:13]Slash API SL user from this our uh application will understand it it has to be this API pattern has to be routed to user router so which is that user router this is that user router within user router for in user itself you can have perform different types of task right create user delete user update user so to identify which controller we need need to navigate it we for create user we are to navigate it to create user controller we need to know if it is uniquely identify that right so I'm going to add create for that controller to uniquely identified that controller so adding it as a create now
[4:59]If you go and in our Postman uh just I will refresh the applic I have to refresh the application see we need to ref refresh the application again and restart the application again and again right so to avoid this I have an uh I would suggest do installing node mod which I will explain it to in a while but in the in the meanwhile we'll just check it how this post is now working okay so if I send the same post request right now it will give out an error because I have changed it to for uh we have given it an a URL pattern
[5:42]That is that/ API slash users which means from this it will understand it should be going to the user router within user router it has to perform the create user task the the create user controller so it has to be navigated to the create user control that is why it is create and if I send it see now we got the response that we desired now and to actually if you don't want to restart the application again and again the only when afterwards every time we make a change and save it the application will itself understand it and actually the uh restart the application for that we
[6:33]Need to install a dependency called uh node modon to install it nothing we we need to do just exit the uh application and give this command npm install node mod it might take some time to install yes it's to check it if it is installed you can go and open the package J you can see how we install Express in last lecture it has installed node one into our dependency but one thing uh we need to notice uh while we are actually deploying this into
[8:30]If you add it it will add it into your dep dependency so that our application will be will know it is only during the development process we need this and it won't uh be used in our uh during our uh deployment phase that's see see you can see it is added into the dev dependency over here after this we just need to add it in the scripts I'm going to start node mod our applications app.js that's it if you just do this and actually start our application no npm start give this command npm start it is just starting our application wait for a second yeah see node one app.js is
[9:39]Running and when we get the server is up and running command that means our application has successfully started yeah starting node This Server is running on port 8080 so if if you can actually see here if I make a small change over here in our uh development it will be directly reflected over there in this uh server we need not restart the application again and again see I will change it like create user instead of create I'm going to add it as create user yes and I also need to do that in the controller part create L see if you after doing that if you
[10:31]Just go and see check in the terminal it is again restarting the it already restarted while we saved in the rout routers user.js now in controlers also when we saved it is again running the server and now the server is running successfully in port 8080 see so we need not again and again restart the application that's the advantage of node mod so moving on um uh from our front end that is the instead of front end now we are actually using the postman we need to send if we need to send an information from uh front end to the back end API how we will send it to send uh we'll send it
[11:13]Through our payload that is like the payload will be sent in a Json format here we are sending a raw data uh for creating user just the have this data name this test and then email test at gmail.com and then password here for basic purpose we are sending it directly but while we for safety purpose while we actually send an password from front end to back end we have to Hash the password that is how we do do it in a professional environment so sorry from here if I click Send yeah this uh
[12:25]Uh this payload is sent to the back end API but we we are not we need to print it to check if we received it perfectly so in to see the payload what we need to do is inside our controller the response is the one that we are sending you can check here right what is this request that is another argument in this function the request is what the front end uh or the API requ the request will send you in the request body we check you can check in the postman we are sending it inside the body right here if you can see it is inside the body so
[13:06]What we need to do is console. log request dot body that's it if you just uh do this uh and see your application is re restarting by by itself application is started now if we send an AP request this successful over here but we let's check if it has printed the request. what see we are getting an undefined because we don't our application didn't know what type of data is being sent we need to know if it is a Json format or any what format is it is being sent for that you just need to add one command over here in app.js that is app. use similar to the one the down
[14:13]Express dot Json that's it if you add this command and actually save it will restart restart the application now if we send send a request uh AP request see in the terminal see we got name test name is test and email test gmail.com password in the backend server from front end we have communicated to the back end so the next process is to communicate from our back endend to our database so how to connect from connect our front backend AP to database uh in our case it is mongod DV right so for that we are using Magus dependency this dependency is similar to like hibernate
[15:19]Orm for a spring uh spring boot application so it will help us avoid all the boiler plate cloths and just uh we need to run queries that we need to we need when when when a requirement arises for that connecting to the database you need to uh we are following MSC pattern so I'm going to add a folder called DB inside the DB I'm going to create an index.js file before that we need to install the dependency so for that uh just exit the application and then we need to install npm install mongus
[16:57]E this is a big package so it is taking quite long time yes yeah it is compl yeah completed with zero vulnerabilities you can check again in package. Jon mongos is added to the dependencies now inside my database I need to give give this command const Mangus equal to
[18:10]Require mango this is I actually take care if Mangus is actually used in this uh index.js page after that we need to add the command how to connect with our uh mongod DB database this simple command just mongus dot connect and this will actually do connect with uh we need to enter just the local URI of our database then it will actually connect it to the database how to get the local URI of the database just click onto this uh uh your mongodb compass go over there and just click over here and copy string connection this paste it over here mongodb Local Host slash our database name our
[19:10]Specific database name we are using this movie review so I'm just going to and disconnect process basically an asynchronous process what I mean by asynchronous process that uh the process actually starts uh once it is started we don't wait for the final response to be sent it will be after completing it it will parall completing it it will just send the response only after it completes it but we will actually St say start the process and we will move on to our next steps of in our Cod that's it that is like while initially starting our application itself we will actually say connect to the database and then we'll
[20:01]Start our application we don't have a pro we don't check if the mongus is connected or not in the end if it is connected it will say mango the mongodb database is connected if it is not connected it will say database is not connected and throw error to see that we actually need to add this command dot then and then Arrow function console do log DB connected successfully if it didn't connect uh successfully then we need to look for the error statement so that so for that dot
[21:17]Catch console.log DB connection has some error and you that's it that's it in this file after that we just need to uh in our app.js we need to add this command require do slash DV that's it now our app if you start our application npm start it will actually basically while starting the application itself it will check and
[22:28]If send if it is able to connect with the database or not this might take some time because connecting to database takes quite some time server is running on port 8080 see that command is executed even before uh DB is connect connected command because even though that process has started before itself see this was this require it will itself start the DB connection
[23:38]Process but the next steps has been executed even before the this step is complete that is what is asynchronous processings see okay we have a connection error there's some sort of error that occurred while connecting to mongod DB databas okay see from this error itself you can understand that see eror connection refused this 27 uh 017 means our mango DB URI that is we gave here right yeah that you can check but then what is this colon colon one that colon colon one is like in our local database it is actually uh accessing that uh one if our local local host is 27. 0.0 it is
[24:39]Listening to that first Port like not the port the first uh IP address that is where where but our some mistake is happening So to avoid this we can actually totally remove this Local Host and just enter the IP address directly that is 127 for me it's 127.0.0.1 and if I run it it would have restarted by now the DB is connected successfully see this is how we connect from our backend API to uh to the database so in our next lecture we'll see how we can use the m mongos to actually create an user uh in our database thank you that's it for this
[25:49]Lecture
More videos
2:08Bridging the Pixel Gap in Browser Automation.
2:23How One Narrow Safety Rule Can Make an AI Less Safe Everywhere Else.
2:04Why splitting a chunk from its document makes it retrieve for the wrong question
4:20Three You Can Take Back. One You Can't.
2:21Why a 50-turn agent pays for the same screenshot 35 times unless it caches the pixels
1:53