s24 May 31 Session 5 Full Stack Web Development

In this session, participants learn about NoSQL databases, specifically MongoDB, which uses JSON document storage.
You explore how to set up a MongoDB Atlas cluster, integrate it into a Node.js application using Mongoose, and perform CRUD operations.
Additionally, they benefit frp, using MongoDB Atlas for web and mobile applications, such as scalability, flexibility, and developer productivity. Practical exercises included creating a pet walking service datastore, managing data with Node.js scripts, and building the Pawsitive Care website.
This full-stack web development tutorial covered setting up an Express server, defining Mongoose models, and creating EJS views for a CRUD interface, all connected to a MongoDB Atlas database.
The session aimed to provide a comprehensive understanding of using JSON databases with MongoDB Atlas in modern application development.

Today’s Learning Outcomes:

The completed version of the Pawsitive Care website:

Class Plan:

Part 1 Understand what a MONGO db is : A database product : Free, paid service level
What kind of data storage mechanism does MONGO DB use? JSON document.
JSON : JavaScript Object Notation — This is the data structure for MONGO DB
Part 2: Getting hooked up to MONGODB in the cloud.
Part 3: MONGOOSE Lab: Building the Pet Store
Part 4: Doing CRUD with MONGOOSE APIs.
Data Persistence
Intro to NoSQL databases (Documents and collections)
Signing up for Mongo Atlas
Adding Mongo Atlas to an Express project
Installing Mongoose
Adding the Mongo Connection String
Creating a Model
Creating a Schema
Creating an Express GET endpoint that performs a query (.find, .findById)
MongoDB Documentation:
There are no rows in this table
“Why is it called a NOSql Database?”
Learning to use a Database Product called MONGO.

The data encoding format in MONGO is JSON: JavaScript Object Notation

JSON is a data description language (Just like HTML is a Page Description Language)
With JSON: You can change the shape of the data container dynamically under program control at runtime.
In NODE, we will be using the packages of to manage our Mongo Data Structures.
key3:{ keyx:valuex, keyy, valuey}
In JSON we have collections of { key: value, key2, value2 }
For a SQL database, the database structure is a very complex data structure created and maintained by the database Server.
Building the backend data persistance store for the 3 tier Model View Controller Web Application.
Understanding the SQL Data Store and how it differs from SQL.


Advantages of a Network-Aware Distributed Database like JSON on MongoDB Atlas over a Local SQL Database for Web and Mobile Android Applications

As we continue to develop our web and mobile applications, it’s essential to choose the right database technology. While traditional local SQL databases have their merits, a network-aware distributed database like MongoDB Atlas, which uses JSON as its data format, offers significant advantages for modern web and mobile applications. Let's explore these benefits:

1. Scalability and Performance

Horizontal Scalability: MongoDB Atlas supports horizontal scaling through sharding, which means you can distribute data across multiple servers. This allows your application to handle increased loads and growing data volumes without performance degradation.
Optimized for Read/Write Operations: JSON’s flexible schema reduces the need for complex joins, often resulting in faster read and write operations. This is particularly beneficial for applications that require real-time data processing and quick access to large datasets.

2. Global Distribution and High Availability

Multi-Region Deployment: MongoDB Atlas allows you to deploy your database across multiple cloud regions, bringing data closer to your users. This reduces latency and enhances the user experience for global applications.
Automatic Failover: MongoDB Atlas provides built-in high availability with automatic failover. In the event of a node failure, the system automatically switches to a replica, ensuring continuous availability of your application.

3. Flexibility and Schema Evolution

Dynamic Schemas: JSON documents can easily accommodate changes in data structure without requiring a predefined schema. This flexibility is ideal for agile development environments where application requirements frequently change.
Easier Data Modeling: With JSON, you can represent complex hierarchical relationships and nested data structures naturally, aligning well with the needs of web and mobile applications.

4. Developer Productivity

JavaScript and Node.js Integration: MongoDB’s JSON format aligns seamlessly with JavaScript, making it easier for developers to work within a single language ecosystem. This reduces the learning curve and improves developer productivity.
Rich Query Language: MongoDB provides a powerful query language that supports rich queries, aggregations, and geospatial searches, which are critical for developing advanced features in web and mobile applications.

5. Managed Services and Operational Ease

Fully Managed Service: MongoDB Atlas handles database administration tasks such as backups, patch management, and monitoring, allowing developers to focus on application development rather than infrastructure management.
Automated Scaling and Updates: Atlas offers automated scaling and seamless updates, ensuring your database infrastructure can grow with your application without manual intervention.

6. Security and Compliance

Advanced Security Features: MongoDB Atlas includes features like end-to-end encryption, role-based access control, and IP whitelisting, ensuring that your data is secure both at rest and in transit.
Compliance Certifications: Atlas complies with various industry standards and regulations (e.g., GDPR, HIPAA), making it suitable for applications that handle sensitive user data.

7. Mobile Sync and Offline Access

Realm Mobile Database: MongoDB offers Realm, a mobile database that synchronizes with MongoDB Atlas. This provides real-time data sync and offline access, essential for mobile applications where connectivity may be intermittent.
Conflict Resolution: Built-in conflict resolution mechanisms ensure data integrity and consistency, even when multiple users are interacting with the same data simultaneously.

Practical Application in Web and Mobile Development

For web applications, the advantages of using MongoDB Atlas translate to better performance, easier scalability, and a more flexible development process.
For mobile Android applications, features like real-time sync with Realm ensure a seamless and responsive user experience, even in scenarios with poor or no internet connectivity.
By leveraging MongoDB Atlas, we can build robust, scalable, and high-performance web and mobile applications that meet the demands of modern users. The flexibility of JSON, combined with the distributed nature of MongoDB Atlas, positions us to create innovative solutions that can grow and adapt with our applications.
Let's harness these advantages as we integrate MongoDB Atlas into our development stack, ensuring we build scalable, reliable, and high-performing applications for our users.

Introduction to Using JSON Database Technology with MongoDB Atlas

Welcome to today's session on Full Stack Web Development!
In this class, we will be diving into the world of NoSQL databases with a focus on MongoDB Atlas, a powerful cloud-based solution for managing and scaling our data needs.
As we continue to build our three-tier Model View Controller (MVC) web application, understanding the advantages of JSON as a data model and how to leverage MongoDB Atlas will be crucial for our backend development.

Why “No SQL?’

What is the basis of a SQL database.
Codd’s 13 Laws: Basis of creating a database application to model a business domain:
Identify all the entities in the Business Domain.
Create Tables corresponding to the entities in the Business Domain.
For each table: you identify the attributes of that entity and you create them as fields in the Table.
Normalization to organize the tables: The basis of Normalization is the PRIMARY KEY
Big data is what happens when you don’t have a primary key!

Why Choose JSON and NoSQL over SQL?
Traditional SQL databases use structured tables and schemas to store data, which works well for many applications but can be limiting when dealing with more complex and variable data structures.

Here’s why JSON and NoSQL databases like MongoDB are becoming increasingly popular:
1. **Flexibility**:
JSON (JavaScript Object Notation) allows for a more flexible and dynamic schema design. You can easily store complex data structures and nested documents, which is perfect for modern web applications that need to adapt quickly to changing requirements.
2. **Scalability**:
NoSQL databases are designed to scale out horizontally, making it easier to handle large volumes of traffic and data. MongoDB Atlas, in particular, provides automatic sharding and scaling, ensuring your application remains performant as it grows.
3. **Speed**:
JSON data models can lead to faster read and write operations. MongoDB’s document-oriented approach reduces the need for complex joins and can improve performance for many types of queries.
4. **Developer Productivity**:
Working with JSON feels natural in JavaScript and Node.js environments, reducing the cognitive load on developers and accelerating development cycles.

Getting Started with MongoDB Atlas

MongoDB Atlas is a fully-managed cloud database service that takes care of the infrastructure, security, and backups, allowing us to focus on building our application.
Here's how we'll integrate MongoDB Atlas into our Node.js project:
1. **Signing Up for MongoDB Atlas**:
- Visit the [MongoDB Atlas website]( and create an account.

- Follow the guided setup to create your first cluster.



Setting Up a Simple, Cost-Free MongoDB Atlas Cluster for Today's Lab

For today's lab, we'll focus on setting up a free, simple MongoDB Atlas cluster that's easy for students to use for our proof of concept.
We'll go through the steps to create a "Shared" cluster, which is free and sufficient for our learning purposes.

Step-by-Step Guide to Creating a Free MongoDB Atlas Cluster

Sign Up for MongoDB Atlas:
Visit the and sign up for a free account.
Create a New Cluster:
Once logged in, navigate to the Clusters section in the Atlas dashboard.
Click on Create New Cluster.
Select the Free Tier:
Choose the Shared option, which includes the M0 free tier.
Configure the Cluster:
Cloud Provider & Region: Select any region that offers the free tier. Popular options include AWS (N. Virginia) or Google Cloud (Oregon).
Cluster Tier: Ensure you select the M0 (Free Tier). This option offers 512 MB of storage, which is sufficient for our initial experiments.
Cluster Name:
Give your cluster a name, such as MyFirstCluster.
Create Cluster:
Click on Create Cluster. The setup process may take a few minutes.

Connecting to Your MongoDB Atlas Cluster

Once your cluster is created, follow these steps to connect it to your Node.js application:
Whitelist Your IP Address:
Go to the Network Access section in the Atlas dashboard.
Click Add IP Address and select Allow Access from Anywhere for convenience during the lab. You can refine this later for better security.
Get Your Connection String:
Go to the Clusters section and click on Connect for your newly created cluster.
Choose Connect Your Application.
Copy the provided connection string. It will look something like this:
Replace <username>, <password>, and <dbname> with your actual MongoDB Atlas username, password, and database name.
Install Mongoose:
In your Node.js project, install Mongoose by running:
npm install mongoose
Connect to MongoDB Atlas:
Use the following code to connect your application to MongoDB Atlas:
const mongoose = require('mongoose');

mongoose.connect('your_connection_string', {
useNewUrlParser: true,
useUnifiedTopology: true,
.then(() => console.log('MongoDB connected...'))
.catch(err => console.log(err));


By following these steps, you'll have a free, easy-to-use MongoDB Atlas cluster set up for today's lab. This setup is perfect for getting started and allows you to focus on learning without worrying about costs or complex configurations. Let's get started with creating our cluster and connecting it to our Node.js application!

**Setting Up MongoDB Atlas in Your Node.js Application**:
- **Install Mongoose**: Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js, providing a straightforward way to model your data. Install it using npm: ```bash npm install mongoose
**Add the MongoDB Connection String**:
In your Atlas dashboard, obtain your connection string and add it to your Node.js application.
Typically, this is done in a configuration file or directly in your app’s initialization code.


Now you are setup with the connection credentials to access MongoDB Atlas:

Next steps:

Integrate MongoDB Atlas with Node.js
Lab: Installing Mongoose, adding the connection string, and setting up your first schema and model.
Create an Express GET Endpoint**:
Develop a GET endpoint that performs queries using `.find` and `.findById` methods, allowing you to retrieve data from your MongoDB Atlas database.

Creating and Querying Data**:

- Create schemas and models to represent your data. - Perform CRUD operations (Create, Read, Update, Delete) to interact with your database.

- **Create a Model and Schema**:
Define your data structure using Mongoose schemas and models, which will help in validating and organizing your data.

Connecting to MongoDB Atlas

- Use Mongoose to connect to your MongoDB Atlas cluster.
Here’s a basic example: ```javascript const mongoose = require('mongoose');
mongoose.connect('your_connection_string', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected...')) .catch(err => console.log(err));


The elements of a MONGO data store:

Introduction to JSON Databases Using a Pet Walking Service Example

Welcome and Overview

Welcome, everyone! Today, we're going to dive into the theory behind JSON databases, using our pet walking service as an example. We'll explore how MongoDB, a popular JSON database, stores data and collections, and why JSON is such a powerful format for modern web applications.

What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format that's easy for humans to read and write and easy for machines to parse and generate. JSON is used primarily to transmit data between a server and a web application as text.
Example of a JSON object:
Copy code
"name": "Buddy",
"type": "Dog",
"breed": "Golden Retriever",
"age": 3,
"ownerID": "client1"


Native to JavaScript: JSON is based on a subset of JavaScript, which means it works natively with JavaScript environments. This makes it ideal for use with Node.js and other JavaScript frameworks.
Human-Readable: JSON is easy to read and write for developers, making debugging and data manipulation straightforward.
Interoperability: JSON is language-agnostic, meaning it can be used across different programming languages, making it an excellent choice for web APIs and data interchange.

How MongoDB Uses JSON

MongoDB is a NoSQL database that uses a document-oriented data model. Here's how it works:
Database: The highest level of organization in MongoDB, analogous to a database in a SQL system.
Collections: Collections are analogous to tables in SQL. They group related documents together.
Documents: The basic unit of data in MongoDB, similar to a row in a SQL table, but more flexible. Documents are JSON-like objects, stored in a binary format called BSON (Binary JSON).

Data Model for Pet Walking Service

Let's use our pet walking service to illustrate how MongoDB stores data. We'll have three collections: Pets, DogWalkers, and Clients.
Pets Collection:
Copy code
"name": "Buddy",
"type": "Dog",
"breed": "Golden Retriever",
"age": 3,
"ownerID": "client1"

DogWalkers Collection:
Copy code
"name": "Alice",
"rating": 4.9,
"available": true

Clients Collection:
Copy code
"name": "John Doe",
"contact": ""

How MongoDB Stores Data

Dynamic Schemas: Unlike SQL databases, MongoDB does not require a predefined schema. This means each document in a collection can have a different structure.
Embedded Documents: MongoDB allows for embedded documents and arrays, enabling complex data hierarchies within a single document.
Indexing: MongoDB supports indexing to optimize query performance. You can create indexes on fields within your documents, similar to SQL indexes.

Advantages of Using MongoDB for Our Pet Walking Service

Flexibility: The dynamic schema nature of MongoDB allows us to easily evolve our data model as the application requirements change without needing to modify a rigid schema.
Scalability: MongoDB can handle large amounts of data and high traffic loads by scaling horizontally. This is crucial for applications expected to grow over time.
Speed: JSON documents can be accessed and manipulated quickly, making read and write operations fast, which is essential for real-time applications.

Practical Example: Connecting Node.js to MongoDB

Here's a practical example of how to connect our Node.js application to MongoDB and create our collections.
Install MongoDB Driver:
Copy code
npm install mongodb

Connect to MongoDB:
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://";

const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
) instead.