0% found this document useful (0 votes)
24 views

WebDev Week 10 PPT - Connecting to Databases

This document provides an overview of databases, focusing on SQL and NoSQL types, their features, and use cases. It includes instructions for setting up MongoDB, performing CRUD operations, and connecting Express.js with a database using Mongoose. Best practices for data management and security are also discussed.

Uploaded by

Leona Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

WebDev Week 10 PPT - Connecting to Databases

This document provides an overview of databases, focusing on SQL and NoSQL types, their features, and use cases. It includes instructions for setting up MongoDB, performing CRUD operations, and connecting Express.js with a database using Mongoose. Best practices for data management and security are also discussed.

Uploaded by

Leona Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

WEEK 10

“CONNECTING TO DATABASES”

Presented by Date
Ocean Blue Shark 19 November, 2024
WHAT ARE DATABASES?
A database is like a digital filing cabinet where data is
stored, organized, and accessed when needed. Whether it’s
keeping track of friends on social media or managing
items in an online store, databases are behind the scenes
making everything work smoothly.

There are two main types of databases:


SQL (Structured Query Language): Uses a fixed
structure, like a spreadsheet.
NoSQL (Not Only SQL): More flexible, like a big
notebook where you can write in any format.
WHAT IS SQL?
SQL (Structured Query Language)
SQL is a language used to manage and
manipulate relational databases. These databases
organize data into tables with rows and columns,
where a predefined schema ensures data consistency.
Each table uses a unique primary key to identify rows,
enabling clear relationships between tables. SQL is
highly structured and is widely used in systems
requiring consistent, reliable, and well-defined data
storage, such as financial or inventory systems. It
supports operations like Create, Read, Update, and
Delete (CRUD) using standard commands.
SQL
Features of SQL Databases:
Fixed Format: You need to decide in advance what
information to store.
Consistency: Ensures data is accurate and reliable.
Examples: MySQL, PostgreSQL, and Microsoft SQL
Server.

Use Case: If you're building a system that tracks student


grades in an IT college, SQL would ensure consistency and
prevent data redundancy by using relations between
tables like “Students”, “Courses", and ”Grades”.
WHAT IS NoSQL?
NoSQL (Non-relational Databases)
NoSQL databases are designed to store unstructured or
semi-structured data. They do not rely on a fixed schema,
offering more flexibility and scalability. Data is often organized
as key-value pairs, documents, graphs, or column families,
depending on the database type. NoSQL databases are ideal
for applications requiring rapid scaling or dealing with diverse
data types, such as real-time analytics or IoT systems.
NoSQL
Features of NoSQL Databases:
Flexible Format: You can change or add new data
types anytime.
Scalability: Easily grows with more users or data.
Examples: MongoDB, Cassandra, and Redis.

Use Case: If an IT student is working on a social media


app, NoSQL databases like MongoDB can handle user
profiles, posts, and relationships flexibly and scale easily
as the app grows.
SQL VS. NOSQL
Feature SQL (Structured) NoSQL (Flexible)

Tables with rows and Documents, key-value


Structure
columns pairs, or graphs

Schema (Rules) Fixed and predefined Dynamic and adaptable

Organized, predictable Changing or messy


Best For
data data

Social media, gaming,


Examples Banking, e-commerce
IoT
Setting Up MongoDB

Step 1. Install MongoDB


DownloadMongoDB:
https://www.mongodb.com/try/download/community

Also, download the MongoDB Shell from Tools. Make sure you choose
“msi” in the package.
Step 2. Setting up

Accept terms and conditions.


Click “Complete”.

Click “Next”.
Step 2. Setting up cont.

Make sure to check “Install MongoDB


Compass”.

Then click “Install” and wait.


After installing, click finish.
Step 3. Set Up a MongoDB Database
Click the downloaded MongoDB Shell
from earlier.
Just click next, next, and install.
After Installing, click finish.

In the terminal or command prompt, type:

mongosh

Create a Database:

use myDatabase
Step 3. Set Up a MongoDB Database
Create a Collection:

db.myCollection.insertOne({ name: "Aji", age: 21 })


Step 4. Verify the set up

List Databases:

show dbs

View Collections in a Database:


show collections
Step 5. Secure Database
Create a user with specific roles:
use admin
db.createUser({
user: "username",
pwd: "password",
roles: [{ role: "readWrite", db: "myDatabase" }]
})
UNDERSTANDING CRUD OPERATIONS:
CREATE, READ, UPDATE, DELETE
CRUD is an acronym that stands for Create, Read,
Update, and Delete, representing the four essential
operations used in managing and manipulating data in
databases or applications.
CREATE
Purpose:
Adds new data to a database or storage system.

In SQL:
Performed using the INSERT command (e.g., INSERT INTO table_name VALUES (...)).

In NoSQL:
Commands like db.collection.insertOne() in MongoDB allow inserting data into collections.
READ
Purpose:
Retrieves existing data for viewing or processing.

In SQL:
The SELECT command is used (e.g., SELECT * FROM table_name).

In NoSQL:
Use db.collection.find() in MongoDB to fetch documents.
UPDATE
Purpose:
Modifies existing data entries in the database.

In SQL:
Executed with the UPDATE command (e.g., UPDATE table_name SET column=value
WHERE condition).

In NoSQL:
MongoDB provides db.collection.updateOne() or db.collection.updateMany() for updates.
DELETE
Purpose:
Removes unwanted or outdated data from the system.

In SQL:
Achieved through the DELETE command (e.g., DELETE FROM table_name WHERE
condition).

In NoSQL:
MongoDB uses db.collection.deleteOne() or db.collection.deleteMany() to remove
documents.
BEST PRACTICES FOR CRUD
OPERATIONS
Data Validation: Ensure the input data is correct
before executing CRUD commands to maintain
database integrity.

Security: Protect against SQL injection and


unauthorized access by implementing
authentication and input sanitization.

Performance Optimization: Use indexing and


efficient query structures to handle large-scale
data effectively.
CREATE
Example: You’re building a database for storing the names and grades
of your classmates. When a new classmate joins, you use the Create
operation to add their name and grade to the database.

SQL Example:

NoSQL Example (MongoDB):


READ
Example: You want to know everyone’s grades, so you retrieve the
data stored in the database.

SQL Example:

NoSQL Example (MongoDB):


UPDATE
Example: Alex’s grade was recorded as an “A”, but they improved and
now have an “A+”. You use the Update operation to change Alex’s
grade.

SQL Example:

NoSQL Example (MongoDB):


DELETE
Example: A student named Sam has transferred to another school.
You use the Delete operation to remove Sam’s record from the
database.

SQL Example:

NoSQL Example (MongoDB):


CONNECTING EXPRESS.JS WITH A
DATABASE (USING MONGOOSE)
Mongoose is an Object Data Modeling (ODM) library for MongoDB and
Node.js. It is crucial for bridging Node.js and MongoDB together,
without it, we’d have to work with MongoDB using raw queries, which is
more complex and error-prone. Mongoose simplifies this by letting you
define schemas (blueprints for your data) and providing an easier way
to interact with the database.
CONNECTING EXPRESS.JS WITH A
DATABASE (USING MONGOOSE)

Step 1. Install Node.js


https://nodejs.org/dist/v22.11.0/node-v22.11.0-x64.msi
click and install this on your desktop or laptop, then open.
Click next consecutively until setup is finished.
Create a folder in the desktop or preferred directory.
Create another folder within that folder, this will be the
project folder.
CONNECTING EXPRESS.JS WITH A DATABASE (USING MONGOOSE)

Step 2: Utilizing command prompt


In command prompt (search cmd on start), type:

This will make the project folder active within cmd.


After making the project folder active, type this in cmd:

This will initialize node.js within that folder and create a new package.json file.
After initialization, type this:

This will install express and create multiple files within the folder.
CONNECTING EXPRESS.JS WITH A DATABASE (USING MONGOOSE)

Step 3: Creating and running a basic express app


After the last step, minimize cmd and locate your project folder.
Create a new text file then rename it, your preferred name then
change the extension name to js (e.g. app.js).
Using a code editor (such as vscode), open the file then copy and
paste this code to make a sample express app:
CONNECTING EXPRESS.JS WITH A DATABASE (USING MONGOOSE)

Step 3: Creating and running a basic express app


Save the file then exit the editor.
Go back to cmd, then type this:

This will start the server using node.js


In your browser, search or visit http://localhost:3000. You should
see "Hello, world!" displayed.
CONNECTING EXPRESS.JS WITH A DATABASE (USING MONGOOSE)

Step 4: Connect to Your Database Using Mongoose


Create a new cmd, don’t quit the current one.
In the new cmd, make the project folder active.
After making the project folder active within the cmd, type this:

This will install mongoose within the project folder.


Import mongoose by altering the app.js file, declare this within the
code:
CONNECTING EXPRESS.JS WITH A DATABASE (USING MONGOOSE)

Step 4: Connect to Your Database Using Mongoose


Setup the database connection, to do this, we need to provide and
declare the connection string for the MongoDB instance, add this to
your code:

To establish the connection, we need to use mongoose.connect(),


then handle success and failure with .then() and .catch(): add this to
the code:
CONNECTING EXPRESS.JS WITH A DATABASE (USING MONGOOSE)

Step 4: Connect to Your Database Using Mongoose


To test if node.js is connected to the database, just go back to cmd,
activate the project folder then type this:

The connection status must be ‘1’, if not, refer below for precise
tracking:
0: Disconnected
1: Connected
2: Connecting
3: Disconnecting
THANK YOU!
OCEAN BLUE SHARK
Carable, Luisa R.
De Jesus, Edhiev Harold Ken O.
Iruguin, Angel Jasmin G.
Nogot, Josephine Claire G.

You might also like