Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Notes › Web Development

MongoDB and Mongoose

MongoDB is a NoSQL document database: data is stored as JSON-like documents (BSON) in collections, with a flexible schema. Mongoose is the Node.js library that adds schemas, validation and helpers on top.

SQL vs MongoDB words

SQL MongoDB
database database
table collection
row document
column field
primary key _id (ObjectId, created automatically)
JOIN embedding, or $lookup / Mongoose populate
{ "_id": "66a1f…", "name": "Asha", "skills": ["React", "Node"], "address": { "city": "Jaipur" } }

CRUD in the Mongo shell / driver

db.users.insertOne({ name: "Asha", age: 21 });
db.users.find({ age: { $gte: 18 } }).sort({ age: -1 }).limit(10);
db.users.findOne({ email: "a@x.com" });
db.users.updateOne({ name: "Asha" }, { $set: { age: 22 }, $push: { skills: "SQL" } });
db.users.deleteOne({ name: "Asha" });
db.users.countDocuments({ city: "Jaipur" });
Operator Meaning
$eq $ne $gt $gte $lt $lte comparisons
$in $nin value in a list
$and $or $not logic
$exists, $regex field present, pattern match
$set $unset $inc $push $pull $addToSet update operators

Mongoose: connect, schema and model

import mongoose from "mongoose";
await mongoose.connect(process.env.MONGO_URI);

const userSchema = new mongoose.Schema(
  {
    name: { type: String, required: true, trim: true },
    email: { type: String, required: true, unique: true, lowercase: true },
    age: { type: Number, min: 0 },
    role: { type: String, enum: ["user", "admin"], default: "user" },
    skills: [String],
  },
  { timestamps: true }          // adds createdAt and updatedAt
);
const User = mongoose.model("User", userSchema);   // collection: "users"

Mongoose CRUD

const u = await User.create({ name: "Asha", email: "a@x.com" });
const all = await User.find({ role: "user" }).select("name email").sort({ createdAt: -1 }).limit(20);
const one = await User.findById(id);
await User.findByIdAndUpdate(id, { $set: { age: 22 } }, { new: true, runValidators: true });
await User.findByIdAndDelete(id);
const plain = await User.find().lean();   // plain JS objects — faster for read-only results

Validation errors throw a ValidationError; a duplicate unique key throws error code 11000 — return a 400/409 to the user.

Relationships

Embed data that is read together and small (an address inside a user). Reference data that is large, shared or grows without limit (a user's many posts).

const postSchema = new mongoose.Schema({
  title: String,
  author: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
});
const posts = await Post.find().populate("author", "name email");   // fills in the author

Middleware (hooks) and methods

userSchema.pre("save", async function (next) {
  if (this.isModified("password")) this.password = await bcrypt.hash(this.password, 10);
  next();
});
userSchema.methods.checkPassword = function (plain) {
  return bcrypt.compare(plain, this.password);
};

Indexes

Without an index, queries scan every document. Add indexes for fields you filter or sort by.

userSchema.index({ email: 1 }, { unique: true });
postSchema.index({ author: 1, createdAt: -1 });   // compound index

Too many indexes slow down writes.

Aggregation pipeline

const stats = await Order.aggregate([
  { $match: { status: "paid" } },
  { $group: { _id: "$city", total: { $sum: "$amount" }, orders: { $sum: 1 } } },
  { $sort: { total: -1 } },
  { $limit: 5 },
]);

Stages: $match, $group, $sort, $project, $lookup (join), $unwind, $limit, $skip.

Pagination

const page = Number(req.query.page) || 1, size = 20;
const items = await Post.find().sort({ _id: -1 }).skip((page - 1) * size).limit(size);

When to choose MongoDB

Good fit Prefer SQL
flexible or changing fields, JSON-shaped data many relations and joins
fast development with Node strict consistency across many tables (banking)
large scale with sharding complex reporting queries

Interview one-liners

More Web Development notes