Create a Backend Node App using Express and a Local Database
This post is the second in the series, and continues building the clocking system application backend. We’ll go through connecting a local MongoDB backend to Express in this post.
Before starting, ensure that you have a local MongoDB database set up and running.This post follows the steps in the last one. You can read the last post below:
1. Create your Express App Skeleton
This initial step is housekeeping more than anything; we’ll be creating the folder and its respective files to be used in the following steps. Firstly, create a folder for your backend to call home:
mkdir clocking_system_backend
Navigate into the folder and create two files server.js
and router.js
:
cd clocking_system_backendtouch server.js router.js
Once these files have been created, we need to install Node in the root directory (in my case clocking_system_backend
):
npm init
You can click enter to all the options that come up. This should now give you a package.json file in your root directory alongside your 2 files created in the previous step.
While we’re here at the terminal, you can run the following commands to install some additional packages:
npm install mongodb express cors body-parser
These packages will help with reading, writing, and editing data in your database.
2. Connect your Database to your app (server.js)
We’re now going to start connecting your database to the server.js
file. In server.js
add the following:
server.js file set-up
At the moment, router.js and its functions have not been defined, just imported in. To start defining the functions:
3. Define your CRUD operations (router.js)
Thinking about our app more generally, when we create the frontend, we will want to be able to change data in our database without writing out functionality in the frontend itself. Instead we can define this functionality here in the backend and call on functions in the frontend.
The functionality we need can be defined by CRUD operations, that is Create, Read, Update, and Delete.
In our router.js
we can add these operations to interact with our DB:
4. Ready to Rumble… (Serve the backend)
Now that everything’s in place we can serve the backend, in your terminal type:
npm run start
If you navigate to your browser and go to the following URL:
http://localhost:4000/api/staff
Viola! All are staff are here (at the moment it’s just Bob, but we’ll add more in the next story)
To view the final backend repo for this project, click here.
If you have API testing software like Postman or Insomnia (both free!), you can start CRUD operations on the data rather than just reading the data.