The goal of this assignment is to implement database access on the backend and drop the in-memory list of users which was our initial solution to represent data.
To do that, we’ll be using MongoDB as our database management system and Mongoose.js as our JavaScript library to connect to MongoDB and perform database operations.
First we’ll install MongoDB, and then create a database. Once that is working, we’ll move back to our own code repo, install mongoose into our Express server, and connect our app to Mongo. This will allow us to persist the changes that we make to the data, instead of losing our changes whenever the server reboots
1- Setting up MongoDB
There are two ways to work with MongoDB. One option is to install an instance of MongoDB locally. The other option is to set up a MongoDB instance on the cloud. There are pros and cons to each of these options. But since you will need to have a cloud database for your team project, we will use the cloud installation of MongoDB, which is called Cloud Atlas.
If you already have Mongo installed on your laptop, you can create your database there instead.
Here are the steps to create a database on Atlas:
-
Create a MongoDB account on https://cloud.mongodb.com.
-
Then follow the instructions to create an organization and a project. Your database instance will live inside a project.
-
Still on Atlas, once you have a project inside an org, select Build a database. Select the following options:
- Cluster Tier: M0 Sandbox (free)
- Cloud Provider: Azure
- Region: California (westus)
- Cluster Name: up to you; I called mine
Blazing
- Set up database access: Once you have a database create a user (See the Database Access menu option under Security ). Before leaving the page where you create the user, copy down the username and password. You will need it in steps 2 and 5 below.
Note, this username/password is only used to access databases in your organization. Don’t confuse with your user account to access MongoDB as a whole, which also lets you create more projects and databases.
- Set up Network access: Now, it’s time to set up an allow-list of IP addresses. Go to the Network Access menu option. For development purposes, add an entry to allow connections coming from any IP address (0.0.0.0).
This is reasonable for a class project. In a production environment with real users, you would add only specific IP ranges or IP addresses based on the node(s) your backend is running.
2 - Installing and using Mongo Shell
While our application will use a Javascript SDK to work with Mongodb, it’s also useful to have a command line way to do things like create databases and load sample data. We will use a tool called mongosh (for Mongo Shell).mongosh
The page [mongodb.com/docs/mongodb-shell/install] contains instructions on how to download and install Mongo Shell. It will depend on your OS.
If you’d rather use a GUI-based tool to work with your database, you can download and install Compass instead of
mongosh. It’s up to you. I’ll present the instructions formongoshhere; if you use Compass, you’ll have to locate the equivalent functions in the UI.
Once mongosh is installed, you can go ahead and open Mongo Shell by running the mongosh command on the terminal. You can find this command by going to the Overview screen for your database on MongoDB, and clicking the [Connect] button. This will bring up a dialog showing you various ways of connecting. Choose the one called Shell, and you will see a command like this.
mongosh "mongodb+srv://blazing.yf76vub.mongodb.net/" --apiVersion 1 --username student
Your command will have a different host name and username.
You will be prompted to enter your database password, which you should have from Step 1.
In Mongo Shell you’re able to run commands that can perform all sorts of operations on databases, such as creating or dropping a database, creating collections (in mongodb a collection is a group of documents within a database), and inserting/updating/deleting documents in collections.
For instance, on Mongo shell, to show the databases you can run
show dbs
To see which database your commands will run in, you can run:
db
Let’s create our own database called ‘users’:
use users
If you run “db” again you’ll see you’re now at “users”. Then, we’ll create a collection and insert our first document in a single line. MongoDB does not create a collection effectively if there’s no document in it.
db.users_list.insert({"name":"Charlie", "job":"Janitor"})
The command above will create a collection called “users_list” in our loaded db (“users”) and add to the collection the new document we’re passing as an argument. As you can see, the document follows the JSON format.
The Mongo API is extensive. There are many more commands and usually there are multiple ways to do some of the supported operations.
Consider these links to learn new commands:
[docs.mongodb.com/manual/crud]
[docs.mongodb.com/manual/mongo/#the-mongo-shell]
[docs.mongodb.com/manual/reference/method]
[docs.mongodb.com/manual/reference/mongo-shell]
[docs.mongodb.com/manual/tutorial/getting-started]
3 - Installing Mongoose
Our previous assignment dealt with MongoDB installation and a few commands to get familiar with MongoDB programming interface using mongo shell. Nearly all the operations available on the MongoDB Shell are also available programmatically through Mongoose.
For this lab, you can either work on a new project folder or continue working on your past backend project folder. In either case, please continue work in your existing monorepo, and put your new work on a separate branch.
To install Mongoose, on your express-backend folder, run
npm install mongoose
Your can find all the documentation about Mongoose here.
4 - Starter Code
I’ve provided a starter code to represent our Model component in an MVC architecture. The model is supposed to encapsulate database access and the data representation of our business entity (User).
The code that was presented in class is in my github (username: laranicholsbrown). In the models/user.js file, you’ll see our database schema definition. This is the Model in our MVC architecture.
Our Express app, defined in backend.js, is the Controller and does not access the schema directly, leaving this concern to the model. Also, our model component does not care about receiving requests and sending responses to “clients”. This separation of concerns is important for establishing a good level of modularity and improving system maintainability as the design evolves.
Create the models and services directories in your express-backend packages and copy the files models/user.js and services/user-service.js from the repo. Your package should now have a structure like this:
express-backend
├── backend.js
├── models
│ └── user.js
├── package.json
└── services
└── user-service.js
To convert your existing backend.js code, replace the helper functions which manipulated the users data with functions imported from user-services.js. Note that the new functions return a Promise so be sure to modify their call sites to use .then and .catch. You should then be able to remove the users data structure from the backend entirely—from now on the data will live in MongoDB.
You may notice that some
mongoosefunctions return a mongoose Query which is not exactly the same as aPromise, but you can still use.thenand.catchwith them.
5 - Connecting to Atlas from mongoose
Before you can call any of the mongoose APIs, you need to connect to your database. You do this with mongoose.connect, which takes a Connection String as a parameter.
To discover your connection string, go to Database Overview page on Cloud Atlas. Find your cluster’s name (it’s probably the only one) and click on the Connect button next to it. In the window which pops up, choose Drivers under Connect your application and you’ll see an example of the database URI (aka connection string). This is the string you’ll use locally when you run your project.
If you look at the connection string, you will see that it contains your password. You should NEVER put the connection string itself into your Javascript files, because when it gets checked into git and pushed to GitHub, anybody can see it and can use it to modify your data.
Even if your repo is private, that does not make it secure enough. Repos are not encrypted on Github, and they may be viewable, for example, by engineers who operate Github. So you should never put passwords into
git.
What you need to do instead is Create a .env local file in your backend subpackage (not at the root of your project). Your express backend will read this file when it connects to your database. In it, you should define an environment variable MONGO_CONNECTION_STRING and assign it the value which you got from the MongoDB Connect dialog.
Your .env should look something like this:
MONGO_CONNECTION_STRING=mongodb+srv://nichols:password@blazing.yf76vub.mongodb.net/
Of course, you need to replace my connection string with yours. If your connection string has a ? followed by some parameter assignments, remove everything from the ? to the end. Also, notice there can be no spaces around the = sign.
Important!: you should never commit your .env file to git. The best way to enforce this is to add .env to your .gitignore.
Now, you’re going to use a package called dotenv to read your .env file and provide the variable(s) there to your app through the process’ environment variables.
First, add the following two imports to your backend.js:
import dotenv from "dotenv";
import mongoose from "mongoose";
and then, before the line const app = express(), add the following:
dotenv.config();
const { MONGO_CONNECTION_STRING } = process.env;
mongoose.set("debug", true);
mongoose
.connect(MONGO_CONNECTION_STRING + "users") // connect to Db "users"
.catch((error) => console.log(error));
You want to start the connection early because it can take some time. It runs asynchronously, so your app can go on and initialize all your routes while the connection is still getting started.
Now you can test your backend and see that it returns the data you manually entered into MongoDB.
6 - Evolving the Code
If you note, our Express backend is partially using our new design (with database access). There are four actions using the database:
GET /users to fetch all the users.
GET /users?name=<name> to fetch users by name, and GET /users?job=<job> route to fetch users by job
POST /users to create and insert a new user
GET /users/<id> to fetch user by id
Now, it’s your turn to evolve the code and make it use the database for all supported actions. Therefore, you will implement the following two actions using the database access.
GET /users?name=<name>&job=<job> to fetch users by matching both name and job. See how findUserByName and findUserByJob are implemented in user-services.js and modify to apply both conditions at once.
DELETE /users/<id> to remove a user, given their id.
Use the mongoose function []findByIdAndDelete](https://mongoosejs.com/docs/api/model.html#Model.findByIdAndDelete). Remember to follow the architecture (and maintain the separation of concerns). In the end, you should not use the internal in-memory user list anymore. Test your backend routes to make sure they’re behaving as expected. Now, check the next step to make your frontend compatible with this version of your backend. You should also manually test the application through the React frontend.
7 - Adjusting the FE to make it compatible with _id
Before working with MongoDB, we were using the id field. With mongo, we’re utilizing the built-in _id field. Note the difference in their names. To avoid unnecessary conversions between id and _id, you can change your FE to use _id as the id field. Just look through your FE code and check where you need to change from id to _id. It really depends on how your FE is implemented (I’ve seen students passing the id value in different ways). The “ID” column name on the table header can stay as “ID” (no need to change it to _id).
Now, you have an MVC app using React on the frontend (View), NodeJS/Express on the backend (controller functions exposed as REST API endpoints), and also on the mongoose/MongoDB to represent our Model and persist the data. This is just one of the many other ways to implement an MVC app.
8 - Turn it in
As with the other assignments, you can turn it in on Canvas by submitting your Github URL. Make sure the URL you submit has the correct branch included.
Since our grader will not have your Mongo connection string, they will not be able to run the code against your Mongo database. Instead, they will use their own connection string and test your app against this scratch database.