---
# System prepended metadata

title: 'Monday : Introduction to Mongo Database'

---

# Monday : Introduction to Mongo Database

## Overview

![meme](assets/ftw/week7/monday/backend.jpg)

Today we will start uncover the last piece of our Web Development puzzle with the introduction to Mongo DB.

### Agenda

1. E-commerce Front End Presentation
2. Review : Visualize web development
3. Fundamental of Database
4. Introduction to Mongo DB

### Resources

- Download and install MongoDB Community Edition ([Windows](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/))
- Download and install MongoDB Community Edition([Mac](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/))
- Grab this free and easy certificate from MongoDB [M001 course](https://university.mongodb.com/courses/M001/about)

## Presentation time

We will be the judges for our classmate projects. By observing other projects, our ultimate goal is to be able to identify strength that we could learn from as well as weakness that we should avoid making. Also, able to bring up discussion on future improvements such add adding feature , visual effect our eliminating pottential bugs is beneficial to our own skills development.

These are some suggested questions we should ask ourselves while other presenting :

- Is the UI design clean ? (ease to the eyes, no cluster or too overboard layouts, effect )
- Given specific feature of the web, could we re-engineer the solution ? and is it the best way to do it?
  (e.g Search fuction : is the search input controlled? is the search input call the best API ? how many APIs call? how many time React rerender )
- Is the web complete ? (enough core functions of a general web in this category)
- What is one thing you want to ask about this project ?
- What is one thing you want to learn from this project ?
- What is one thing you want to change from this project ?
- Will you use this website ?

## Before we start

### Web Application Flowchart

This is my attempt to visualize a software application flow. ([Web](https://drive.google.com/file/d/1MVMe9beS054L2ETMAHXGgfZYJ4ozbTA9/view?usp=sharing))

![flow](assets/ftw/week7/monday/web.png)

## Database

### Definition

"In computing, a database is an organized collection of data stored and accessed electronically from a computer system. Where databases are more complex they are often developed using formal design and modeling techniques.

The database management system (DBMS) is the software that interacts with end users, applications, and the database itself to capture and analyze the data. The DBMS software additionally encompasses the core facilities provided to administer the database. The sum total of the database, the DBMS and the associated applications can be referred to as a "database system". Often the term "database" is also used to loosely refer to any of the DBMS, the atabase system or an application associated with the database.

Computer scientists may classify database-management systems according to the database models that they support. Relational databases became dominant in the 1980s. These model data as rows and columns in a series of tables, and the vast majority use SQL for writing and querying data. In the 2000s, non-relational databases became popular, referred to as NoSQL because they use different query languages." \_[wikipedia](https://en.wikipedia.org/wiki/Database)

Both a database and its DBMS conform to the principles of a particular database model. "Database system" refers collectively to the database model, database management system, and database.

We choose NoSQL. The reason : "Beginner friendly yet as effective as the other". Eventually, it is recommended that , as a developer, we should have basic knowledge on both systems. So for those who have FOMO (Fear-Of-Missing-Out), feel free to study both.

### SQL vs NoSQL

| System | Pros                                                                                                                                      | Cons                                                                                          |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| SQL    | Flexible queries, Reduced data storage footprint, Strong and well-understood data integrity semantics                                     | Rigid data models, Limited horizontal, Single point of failure scalability                    |
| NoSQL  | Scalable and highly available, Flexible data models, Dynamic schema for unstructured data, High performance, High-level data abstractions | Distributed systems have distributed systems problems, Lack of flexibility in access patterns |

[Read more](https://www.ibm.com/cloud/blog/sql-vs-nosql)

## What Is MongoDB?

![mongo banner](assets/ftw/week7/monday/banner.jpg)

MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need.
As a DataBaseManagementSystem software, MongoDB provide various functions that allow management of a database and its data which can be classified into four main functional groups:

- Data definition : Creation, modification and removal of definitions that define the organization of the data.
- Update : Insertion, modification, and deletion of the actual data.
- Retrieval : – Providing information in a form directly usable or for further processing by other applications. The retrieved data may be made available in a form basically the same as it is stored in the database or in a new form obtained by altering or combining existing data from the database.
- Administration: Registering and monitoring users, enforcing data security, monitoring performance, maintaining data integrity, dealing with concurrency control, and recovering information that has been corrupted by some event such as an unexpected system failure

[Mongo DB official document](https://docs.mongodb.com/guides/)

## Get started with MongoDB Atlas

- Select Create an Organization

![assets/ftw/week7/monday/create_org.png](assets/ftw/week7/monday/create_org.png)

- Name your Organization `MDBU`. Make sure that your cloud service is _Atlas_, then hit Next.

![assets/ftw/week7/monday/org_name.png](assets/ftw/week7/monday/org_name.png)

- Hit Create Organization

![assets/ftw/week7/monday/org_members.png](assets/ftw/week7/monday/org_members.png)

- Hit New Project

![assets/ftw/week7/monday/create_proj.png](assets/ftw/week7/monday/create_proj.png)

- Name your Project `M001` and hit Next

![assets/ftw/week7/monday/proj_name.png](assets/ftw/week7/monday/proj_name.png)

- Select Create Project

![assets/ftw/week7/monday/proj_members.png](assets/ftw/week7/monday/proj_members.png)

- Select Build a Cluster

![assets/ftw/week7/monday/create_cluster.png](assets/ftw/week7/monday/create_cluster.png)

- Select the left-most option that is FREE and hit Create a cluster

![assets/ftw/week7/monday/free_tier.png](assets/ftw/week7/monday/free_tier.png)

- Select the region that is geographically closest to your location. On the bottom of the page change the cluster name to `Sandbox`. Create the cluster. _This step might take a minute or two to complete._

![assets/ftw/week7/monday/name_cluster.png](assets/ftw/week7/monday/name_cluster.png)

- Now that you have an Atlas cluster you need to grant access to your IP Address and create a Database User.
  - Select Connect from the cluster view.
    ![assets/ftw/week7/monday/cluster_connect.png](assets/ftw/week7/monday/cluster_connect.png)
  - Select the _right-most_ option Allow Access from Anywhere and confirm your selection by clicking on Add IP Address. Allowing access from anywhere is not\* a good security practice. Clusters that are used for production should \*\*not have this enabled.
    ![assets/ftw/week7/monday/allow_access.png](assets/ftw/week7/monday/allow_access.png)
  - Create a Database User, then click on Create Database User
    ![assets/ftw/week7/monday/create_user.png](assets/ftw/week7/monday/create_user.png)
  - Close the Connection menu at the _lower left corner_ of the window.
    ![assets/ftw/week7/monday/access_done.png](assets/ftw/week7/monday/access_done.png)

**Load the [Sample Dataset](https://docs.atlas.mongodb.com/sample-data/sample-training)** (for practicing)

Select the "..." option in the cluster menu -> choose the "Load Sample Dataset" option, then confirm your choice.

![assets/ftw/week7/monday/load_sample_1.png](assets/ftw/week7/monday/load_sample_1.png) ![assets/ftw/week7/monday/load_sample_2.png](assets/ftw/week7/monday/load_sample_2.png)

When the dataset is loaded the graph labeled "Logical Size" on the right side of the screen should go up and display the size of the dataset that is above zero and below _512 MB_. Your graph may look different than the picture below.

![assets/ftw/week7/monday/sample_done.png](assets/ftw/week7/monday/sample_done.png)
{"mode":"full","isActive":false}


## Lab Exercise : Review Routing

### Project structure
Your project folder will look like:

```|- bin/
|- controllers/
    |- auth.controller.js
    |- category.controller.js
    |- order.controller.js
    |- product.controller.js
    |- review.controller.js
    |- user.controller.js
|- models/
    |- Category.js
    |- Order.js
    |- Product.js
    |- Review.js
    |- User.js
|- public/
|- routes/
    |- index.js
    |- auth.api.js
    |- category.api.js
    |- order.api.js
    |- product.api.js
    |- review.api.js
    |- user.api.js
|- .env
|- .gitignore
|- app.js
|- package.json
|- README.md
```
```routes/``` stores ```.api``` files that determine routes end point which is a URI and a specific HTTP request method (**GET**, **POST**, and so on). Each route have a handler function which is defined in `.controller` file.
`models/ `stores the schemas that map with the collections in your MongoDB.

### Design the endpoints
In this step, we are designing REST APIs for our application. The main question is how to apply REST principles in design process?

The very first step is identifying the objects which will be presented as resources, which are:

- auth: for authentication process
- category: category of product (create, read, update, delete)
- order: CRUD of orders of users
- product: everything about product 
- review: CRUD of reviews of products
- user: CRUD of user accounts

Next, it's time to decide the resource URIs which are endpoints of our RESTful services. Think about the relationship between resources and its sub-resources (e.g. Product vs Category, User vs Order). 

``` 
/* 
 * @route GET api/products?page=1&limit=10 - Get all products
 * @route GET api/products/category/:id?page=1&limit=10 - Get all products with specific category
 * @route POST api/auth/register - Create a new account
 * @route PUT api/users/me - Update user profile
 * @route DELETE api/reviews/:id - Remove a review
 */
 ```

*Notice*: URIs should be nouns only, don't use any verb or operation like:

```// don't do this
-@route POST api/products/create_blog - Create a new product
```

#### Assign HTTP Methods: 
A user can perform browse, create, update, or delete operations. Typically we assign:

- **GET** for browsing
- **POST** for creating
- **PUT** for updating
- **DELETE** for removing

#### Authorization: 
If there are different roles of users in your system, you should pre-define who can see/do what. Example: we allow everyone to see the list of products so the endpoint will look like:

```
/**
 * @route GET api/products?page=1&limit=10
 * @description Get products with pagination
 * @access Public
 */
 ```
 But if user want to write a review, they need to login, so the endpoint will be defined:

```
/**
 * @route POST api/review
 * @description Create a new review for a product
 * @access Login required
 */
 ```
 
 ### Assignments:
 - Design endpoints for `Product` base on [ecommerce API ](https://coderschool.notion.site/E-commerce-API-Documentation-2c2beec14d1247ce95a62d319d212509)
 - Design all the `Admin required` missing endpoint for the [ecommerce API ](https://coderschool.notion.site/E-commerce-API-Documentation-2c2beec14d1247ce95a62d319d212509)
 - Design at least 2 missing endpoints that you can think of from the e-commerce API
 - Think about schema model for e-comerce project. It's worth to think about it seriously because the database is the core of your application.