Mongoose is a library built on top of the official driver that adds schemas, models, and validation to MongoDB from Node.js — it is the most widely used way teams actually work with MongoDB in real applications.
npm install mongooseimport mongoose from "mongoose"
await mongoose.connect("mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/learningMongo")A schema describes the shape of a document — its fields, their types, and rules like required or a default value:
import { Schema } from "mongoose"
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, default: 18 },
isActive: { type: Boolean, default: true }
})A model is a class built from a schema, giving you a real JavaScript interface for a collection — Mongoose automatically pluralizes and lowercases the name for the actual MongoDB collection ("User" becomes the users collection):
const User = mongoose.model("User", userSchema)// Create
const newUser = await User.create({ name: "Rahul Verma", email: "rahul@example.com" })
// Read
const users = await User.find({ isActive: true })
// Update
await User.updateOne({ name: "Rahul Verma" }, { $set: { age: 25 } })
// Delete
await User.deleteOne({ name: "Rahul Verma" })CRUD method names carry over from the raw driver
Mongoose methods largely mirror the raw driver's CRUD method names, so everything from earlier lessons transfers directly — the real value Mongoose adds is the schema, validation, and default values sitting in front of every write.