3 Hours

10. MongoDB Basics

Database

What is MongoDB?

MongoDB is a NoSQL document database. Instead of tables and rows (like SQL), it stores JSON-like documents. This is a natural fit for Node.js because you work with JavaScript objects natively.

Documents vs SQL Tables

In SQL, you define a strict schema with columns like id, name, age, email. Every row must have exactly those columns. In MongoDB, each document is a flexible JSON object. Different documents can have different fields, and you can nest objects and arrays inside.

JavaScript
// MongoDB Document (flexible schema)
{
    _id: ObjectId("507f1f77bcf86cd799439011"),
    name: "Alice",
    age: 25,
    email: "alice@test.com",
    address: {           // Nested object
        city: "New York",
        zip: 10001
    },
    hobbies: ["reading", "coding"]  // Array
}

Connecting to MongoDB with Mongoose

Mongoose is an ODM (Object Data Modeling) library for MongoDB. It provides schema validation, model methods, and helps organize your database code. The connect() method connects to your MongoDB server.

JavaScript
const mongoose = require('mongoose');

async function connectDB() {
    try {
        await mongoose.connect('mongodb://localhost:27017/myapp');
        console.log('Connected to MongoDB!');
    } catch (err) {
        console.error('Connection failed:', err.message);
    }
}

connectDB();

Defining a Schema

A schema defines the structure of your documents: what fields exist, what data types they have, and validation rules. Even though MongoDB is flexible, schemas help prevent bugs by validating data before it's saved.

JavaScript
const userSchema = new mongoose.Schema({
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    age: { type: Number, min: 13, max: 120 },
    createdAt: { type: Date, default: Date.now }
});

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

Creating Documents (INSERT)

Use .create() to insert a new document into a collection. Mongoose validates the data against your schema before saving. If validation fails, it throws an error.

JavaScript
const User = mongoose.model('User', new mongoose.Schema({
    name: String, email: String, age: Number
}));

async function createUser() {
    const user = await User.create({
        name: 'Alice',
        email: 'alice@example.com',
        age: 25
    });
    console.log('Created user:', user.name, 'with ID:', user._id);
}

createUser();

Reading Documents (FIND)

Use .find() to retrieve documents. You can pass a filter object to narrow results. .find() returns an array. .findOne() returns a single document or null.

JavaScript
async function findUsers() {
    const allUsers = await User.find();
    console.log('Total users:', allUsers.length);
    
    const adults = await User.find({ age: { $gt: 18 } });
    console.log('Adults:', adults.length);
    
    const alice = await User.findOne({ email: 'alice@example.com' });
    console.log('Found:', alice?.name);
}

findUsers();

Updating Documents (UPDATE)

Use .findByIdAndUpdate() to find a document by ID and update it. The { new: true } option returns the updated document instead of the original. Without it, you get the document before the update.

JavaScript
async function updateUser(userId, newAge) {
    const updated = await User.findByIdAndUpdate(
        userId,
        { age: newAge },
        { new: true }
    );
    console.log('Updated age for:', updated?.name);
    return updated;
}

Deleting Documents (DELETE)

Use .findByIdAndDelete() to delete a document by ID. It returns the deleted document, so you can confirm what was deleted. Use .deleteMany() to delete multiple documents based on a filter.

JavaScript
async function deleteUser(userId) {
    const deleted = await User.findByIdAndDelete(userId);
    
    if (deleted) {
        console.log('Deleted user:', deleted.name);
    } else {
        console.log('User not found');
    }
}

Knowledge Check

Ready to test your understanding of 10. MongoDB Basics?

Back