Now that we’ve tackled the concepts, let’s visualise how they are intertwined.
To explain the image above. When the user first triggers the /users end point, it will trigger the route through the server application which is the file that holds the server.
In my case, the server resides in the app.js file. How do I know that it is my server? Because it is where the instance of the server is declared:
const app = express();
On top of that, app.js holds the database connection as well as the grouping routes. Since app.js is like the centre point of everything, it is in our best interest to understand what should be included within it.
First, we must declare ALL the required modules such as the express and mongoose at this point, like so:
//! Required Modules
const express = require('express');
//* This allows us to connect in our mongoDB
const mongoose = require('mongoose');
//! Port
const port = 4000;
//! Server
const app = express();
After declaring them, we then need to create a database connection first and foremost by utilising mongoose and use the dot notation to access the method called connect which allows us to connect to MongoDB Atlas remotely.
The first parameter should have the URI string taken from their site (https://cloud.mongodb.com/) after logging in. Locate the Database under the Deployment and click Connect and then click the Connect your application option from the given tools, then copy the URI string displayed.
The second parameter is optional, but it is ideal to add it in order to prevent the web application from crashing when MongoDB updates. See the full code below:
mongoose.connect(
//mongodb+srv://CG:admin@cluster0.322.mongodb.net/tasks182?retryWrites=true&w=majority
'mongodb+srv://admin:admin@233-course-booking.g54.mongodb.net/tasks182?retryWrites=true&w=majority', {
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
After creating the connection, the programmer has to know if a connection has been established successfully or not, right? In order to do that, we need to access the .connection method that is made available for us by mongoose and declare it in a variable like so:
//This will create a notification if the db connection is successful or not.
let db = mongoose.connection;
We can then tap the variable declared and check if the connection is successful or not by using the .on and the .once methods. What exactly are they?
.on signifies that the event will be called every time the specified event occurs.
.once signifies that the event will be called only ONCE the first event is triggered.
Let us first have a look at the .on code below:
db.on('error', console.error.bind(console, 'DB Connection Error'));
Notice that we’re constantly checking for any error that may occur whilst the server is on as its first parameter. The second parameter is binding the error to both the console and the terminal.
Let us now have a look at the .once code below:
db.once('open', () => console.log('Successfully connected to MongoDB'));
In the code above, we’re checking if the connection is successful or open then we’re logging a message to the console which notifies the programmer that a connection has been established.
The next thing we’re tackling are the middleware that we need in order for our application to run smoothly. The first middleware is the express.json(), its sole purpose is to convert the request body into a JSON object. The next middleware is the express.urlencoded which enables the server to accept any data type on top of the string and array data types that it’s already accepting. Let’s have a look at their code snippets:
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
Now, all we need to add to complete our app.js is to add the grouping routes which will allow us to connect our routes to the server. As shown in the image previously, by visiting the /users, we’re triggering our routes.
Now, what do they look like and how does it work? Let’s have a look at the code snippet below and then dissect what each of them do.
First, we’re declaring a variable that will hold the route (green box above). Next, we’re requiring the routes that we want to trigger (beige colour) which resides in a different file path which is relative to the root file (app.js).
We’re now going to use the routes as a middleware which will run after the request is received and before the response is triggered (app.use). The first parameter is the endpoint (orange box) that we want to trigger our route (yellow box).
Lastly, all we need in our app.js is to add the port:
app.listen(port, () => console.log(
Listening to port: ${port}));
Route file
The route file is where we are going to trigger the business logic which resides in the controller. In this file, we first need to declare the required modules just like what we did in the app.js. The first module we need is the express.
const express = require('express');
The next module that we need is the router which will allow us to access HTTP methods without directly connecting to the server which is declared in our app.js.
const router = express.Router();
But why do we need it instead of just declaring another server you say? Well, it’s because by doing so, we’re not really separating the concerns that we’re trying to achieve.
After declaring the router, we now need to declare the controller that we need to execute which resides in a relative folder; accessed through the relative path using “../”.
const usersController = require('../controllers/usersController');
Now need to execute the controller that holds the business logic for the /users endpoint. However, let us first understand what’s happening with the code below:
router.post('/', usersController.createUsers);
Top comments (0)