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

MongoDB

A Database (DB) is a structured system for storing and managing data, enabling efficient data operations. MongoDB is a NoSQL database that uses a flexible JSON-like format for data storage, contrasting with MySQL's table-based structure. Mongoose is a JavaScript library that simplifies interactions with MongoDB by providing a schema-based structure for data validation and CRUD operations.

Uploaded by

xeroxxwala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

MongoDB

A Database (DB) is a structured system for storing and managing data, enabling efficient data operations. MongoDB is a NoSQL database that uses a flexible JSON-like format for data storage, contrasting with MySQL's table-based structure. Mongoose is a JavaScript library that simplifies interactions with MongoDB by providing a schema-based structure for data validation and CRUD operations.

Uploaded by

xeroxxwala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

What is a Database (DB)?

What is a Database?

A Database (DB) is a structured way to store and manage data. It allows


applications to store, retrieve, update, and delete data efficiently.

🔹 Why do we need a Database?


● To store user details (e.g., name, email, password, etc.).

● To retrieve data when needed.

● To manage large amounts of data efficiently.


What is MongoDB?
🔹 Introduction to MongoDB

● MongoDB is a NoSQL database, meaning it doesn’t store data in tables like SQL
databases.
● It stores data in JSON-like format called Documents.
● It is scalable, flexible, and widely used in modern web development.

🔹 Key Features of MongoDB

1. NoSQL: Stores data in documents, not tables.


2. Schema-less: No need to define a strict structure.
3. Scalable: Handles large amounts of data.
4. Fast Performance: Optimized for high-speed queries.
{
"_id": "64e1b3f7f5a123abc789",
"name": "Alice",
"email": "[email protected]",
"age": 25
}
Difference Between MongoDB and MySQL
Database Type: MongoDB is a NoSQL document-oriented database, whereas MySQL is a
relational SQL database.

Data Storage: MongoDB stores data in JSON-like BSON documents, while MySQL stores
data in structured tables with rows and columns.

Joins: MongoDB does not support traditional SQL joins but uses embedding and
referencing, whereas MySQL relies on JOIN queries to connect multiple tables.
How MongoDB Works
Instead of tables and rows like MySQL, MongoDB stores data as collections and documents.

In MySQL (SQL - Table Format)


In MongoDB (NoSQL - JSON Document Format)
{
"_id": "1",
"name": "Alex",
"age": 25,
"city": "NYC"
}
Installing MongoDB
🔹 Install MongoDB Locally

1. Download MongoDB Community Edition from MongoDB’s official website.


2. Install MongoDB and start the service.

🔹 Using MongoDB Atlas (Cloud)

If you don’t want to install MongoDB locally, you can use MongoDB Atlas (a cloud-based MongoDB
database).

1. Sign up at https://www.mongodb.com/atlas.
2. Create a free cluster.
3. Get your MongoDB connection string.
What is Mongoose?
Mongoose is a JavaScript library that helps you connect your Node.js application to a
MongoDB database and makes working with the database easier.

Key Features of Mongoose

✅ Schema-based: Defines a structure for your MongoDB documents.


✅ Data Validation: Ensures that the data follows a specific format.
✅ Middleware (Hooks): Runs functions before or after saving data.
✅ Built-in Query Methods: Provides easy methods for CRUD (Create, Read, Update, Delete)
operations.
✅ Relationship Handling: Supports references and embedded documents.
Why Use Mongoose?
MongoDB stores data in a flexible JSON format, meaning you can store anything in it. But
without structure, things can get messy.

Mongoose provides a structured way to interact with MongoDB, making it easier to:

✅ Define schemas (structure of your data)

✅ Validate data before saving


How Mongoose Works
1⃣ Connect to MongoDB

Mongoose helps you connect to your MongoDB database.

mongoose.connect("mongodb:userName:password@cluster/myDatabase")

2⃣ Define a Schema (Structure of Data)

A schema is like a blueprint. It tells MongoDB what kind of data you expect.

3⃣ Create a Model (Table in MongoDB)

A model is like a table in SQL databases.


It represents the collection where data will be stored.
Explanation:

● MONGO_URI is a constant variable that holds the MongoDB connection string.


● "mongodb+srv://" → This tells MongoDB to use SRV (DNS Seedlist) for connecting to a
cloud-hosted MongoDB Atlas database.
● biswajeet780 → This is the MongoDB username.
● manager → This is the MongoDB password.
● @cluster0.twcmdeb.mongodb.net/ → This specifies:

○ cluster0.twcmdeb.mongodb.net → The database cluster address (provided by MongoDB


Atlas).

○ / at the end → If no database name is given, it will connect to the default database.

⚠ Security Warning:
Never expose username & password in your code. Store them in a .env file instead.
await mongoose.connect(MONGO_URI); → This waits for MongoDB to connect successfully.

console.log("✅ MongoDB Connected..."); → If the connection succeeds, a success message


is printed.

What is process.exit(1);

process.exit() is a Node.js function that stops the program immediately.

The number inside exit(1) is called an exit code.


Why Use process.exit(1);?

● If MongoDB fails to connect, we don’t want the app to keep running.

● process.exit(1); stops the app completely when an error happens.

What Does 1 Mean?

The number inside exit() is called an exit code:


Without process.exit(1);

If we remove process.exit(1);, the app will keep running, even if MongoDB is not connected.

But we want it to stop if the database is not working.


What is Schema and Model in Mongoose?
In Mongoose, a Schema defines the structure of the documents in a MongoDB collection,
and a Model provides an interface to interact with that collection.

✅ Schema → Defines the structure of data.

✅ Model → Provides methods to interact with MongoDB.


1⃣ What is a Schema in Mongoose?
A Schema is a blueprint for documents in a MongoDB collection. It defines:

✔ The fields (keys) that documents should have

✔ The data types for each field

✔ Validation rules

✔ Default values
🔹 Schemas define the structure of data but do not interact with the database directly.
2⃣ What is a Model in Mongoose?
A Model is a wrapper for the Schema and allows us to interact with the MongoDB collection.

✔ A Model is used to create, read, update, and delete (CRUD) documents

✔ It represents a MongoDB collection

// Create Model from Schema

const User = mongoose.model("User", userSchema);


🔹 Now, User is a Mongoose model that represents the "users" collection in MongoDB.
3⃣ How Schema and Model Work Together?
Schema defines the structure of a document.

Model helps in interacting with the database using that schema.


Create a New File: models/User.js
We will create a User.js file inside the models folder. This file will contain the Schema
(blueprint) and Model (toolbox) for handling users in our MongoDB database.

1⃣ Importing Mongoose

Loads the mongoose library so we can use MongoDB in our Node.js app.

Required to define a Schema and Model.


2⃣ Defining the User Schema (userSchema)

const userSchema = new mongoose.Schema({

Creates a Schema (Blueprint) for how user data should be structured in MongoDB.

3⃣ Defining Schema Fields

Each field in userSchema represents a property in the User Collection.

name:{

type: String

name must be a String.

It is not required, so users can create accounts without a name.


Field: email

email:{

type: String,

unique: [true, "Email already exists"],

required: [true, "Email is required"]

What it does?

● type: String → Email must be a string.


● unique: true → Ensures no duplicate emails exist in the database.
● required: true → Email is mandatory.

● Custom Error Messages:


○ "Email already exists" → If a user tries to register with an existing email.
○ "Email is required" → If a user forgets to enter an email.
role:{

type: String,

enum: ['user', 'admin']

role must be a String.

enum (Allowed values) → Only 'user' or 'admin' are valid.

If someone tries to enter 'manager', it will throw an error.


4⃣ Creating a Mongoose Model

const User = mongoose.model('User', userSchema);


Converts userSchema into a Mongoose Model.

The model is named User (Collection name will be users in MongoDB).

We can use User to add, find, update, or delete users in the database.
Understanding the Two Parameters in mongoose.model()

const User = mongoose.model('User', userSchema);


Here, mongoose.model() takes two parameters:

1. 'User' → The name of the MongoDB collection (Model Name).


2. userSchema → The Schema that defines the structure of documents in that collection.
1⃣ First Parameter: 'User'

● This is the name of the model.


● Mongoose automatically converts it into a plural lowercase collection name in
MongoDB.

2⃣ Second Parameter: userSchema

● This defines the structure (fields & rules) for documents in the users collection.
● The userSchema ensures that:
○ The document must have specific fields (e.g., name, email, mobile).
○ Some fields must be unique (email, mobile).
○ Some fields are required (email).
○ The role field can only be 'user' or 'admin' (enum).
5⃣ Exporting the Model

module.exports = User;
Makes User available for use in other files (e.g., server.js).

Now, we can import this model and use it in APIs.


CRUD Operations (Create, Read, Update, Delete)
Understanding the API (POST /users)

🔹 app.post() → Inbuilt Express function → Creates a POST route.

"/users" → User-defined route → The endpoint where clients send data.

🔹 req → Represents the incoming request (contains data sent by the user).
🔹 res → Represents the response (data sent back to the client).
🔹 async → Used because we are handling database operations (which take time).
Extract Data from Request

{ name, age, email, mobile } → Destructuring (User-defined) → Extracts data from req.body.

req.body → Inbuilt Express object → Contains data sent by the client.


🔹 new User({...}) creates a new instance (document) of the User model. OR

This creates a new user object using your Mongoose model.

🔹 It does not save the data to the database yet! It just prepares the data.

{ name, age, email, mobile } (Object Data)

🔹 Inside {} we pass an object with key-value pairs.


🔹 The keys must match the schema you defined:

The { name, age, email, mobile } values are used to build the new user.

newUser.save()

🔹 newUser.save(); actually saves the document to MongoDB. 🔹 Since saving data is an


asynchronous operation, we use await.
newUser.save()
The .save() method comes from Mongoose, and it's used to store the document (data) in the
MongoDB database.
PUT API – Update User by ID

findByIdAndUpdate
✅ It is a Mongoose method used to:

Find a document by its _id and update it in the database.

Mongoose is a library for MongoDB in Node.js

And findByIdAndUpdate() is a shortcut method from Mongoose to:

1. Find a document (like a user) by its _id

2. Update that document

Syntax: Model.findByIdAndUpdate(id, updateData, options)

You might also like