0% found this document useful (0 votes)
149 views4 pages

Mongodb Mongoose Complete Notes

Uploaded by

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

Mongodb Mongoose Complete Notes

Uploaded by

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

MongoDB and Mongoose Complete

Notes (Easy & Step-by-Step)


Chapter 1: MongoDB Basics
MongoDB is a NoSQL database used to store data in JSON-like documents.
It stores data in collections (similar to tables in relational DBs).
Each collection contains documents with fields and values.
MongoDB is schema-less, meaning flexible and dynamic data structure.

Key Concepts:
- Document: JSON-like object (key-value pairs).
- Collection: Group of documents.
- Database: Container of collections.

Example Document:
{
name: 'Raj',
age: 25,
city: 'Delhi'
}

Installation:
- Download MongoDB Community Server from official website.
- Start MongoDB server using `mongod` command.
- Use `mongo` shell or GUI tools like MongoDB Compass to interact.

Chapter 2: Mongoose (ODM) Introduction


Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js.
It provides a schema-based solution to model application data.
Allows you to define schemas, models, and perform CRUD easily.

Setup:
npm install mongoose

Basic Concepts:
- Schema: Defines structure of documents.
- Model: Represents a collection and provides an interface to interact.

Example:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
age: Number
});
const User = mongoose.model('User', userSchema);
const newUser = new User({ name: 'Raj', age: 25 });
newUser.save();

Chapter 3: CRUD Operations with Mongoose


Create: Insert new documents.
Read: Find documents.
Update: Modify existing documents.
Delete: Remove documents.

Examples:
Create:
const user = new User({ name: 'Sita', age: 22 });
user.save();
Read:
User.find({}, (err, users) => {
console.log(users);
});
Update:
User.updateOne({ name: 'Sita' }, { age: 23 }, callback);
Delete:
User.deleteOne({ name: 'Sita' }, callback);

Chapter 4: Advanced Mongoose Features


Validation: Define rules for fields.
Middleware: Functions that run before/after certain events.
Population: References between collections.
Indexing: Improve query performance.

Example - Validation:
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, min: 0 }
});

Example - Middleware:
userSchema.pre('save', function(next) {
console.log('Before saving:', this);
next();
});

Example - Population:
const postSchema = new mongoose.Schema({
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
content: String
});
Post.find().populate('author').exec((err, posts) => { console.log(posts); });

Chapter 5: Real-World CRUD Example


Setup Express server.
Connect to MongoDB using Mongoose.
Define User schema & model.
Implement Create, Read, Update, Delete API endpoints.

Example code snippet:


const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());

mongoose.connect('mongodb://localhost:27017/testdb');

const userSchema = new mongoose.Schema({ name: String, age: Number });


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

app.post('/users', async (req, res) => {


const user = new User(req.body);
await user.save();
res.send(user);
});

app.get('/users', async (req, res) => {


const users = await User.find();
res.send(users);
});

app.put('/users/:id', async (req, res) => {


const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.send(user);
});

app.delete('/users/:id', async (req, res) => {


await User.findByIdAndDelete(req.params.id);
res.send({ message: 'User deleted' });
});

app.listen(3000, () => console.log('Server running on port 3000'));

You might also like