Real data is connected. A user writes posts, a customer places orders, an employee belongs to a department. How you store those connections decides how simple your queries are and how fast the app is. This lesson covers the choices you have in MongoDB with Mongoose, the indexes that keep queries fast, and an honest comparison with SQL databases, which interviewers love to ask about.
SQL and NoSQL in plain words
A SQL database, such as PostgreSQL or MySQL, stores data in tables with fixed columns, and connects tables with keys and joins. It is strong when data is highly connected and correctness matters, for example banking, bookings and inventory, because it supports strict rules and multi-table transactions. A NoSQL document database, such as MongoDB, stores flexible JSON-like documents in collections. It is comfortable when records have varied shapes, when the data is read as a whole document, and when the structure changes often. Neither is better in general. A good answer in an interview is: *it depends on the shape of the data and the queries*. Many companies use both.
Embed or reference?
In MongoDB you choose for each relation. Embedding puts the related data inside the document, for example the address inside the user. One read returns everything, and it is the right choice when the child data is small, belongs to one parent and is always read together. Referencing stores the id of the other document, like a foreign key. Use it when the data is large, grows without limit, or is shared. A post has an author and may have thousands of comments, so the post holds the author's id and the comments live in their own collection. A document cannot grow beyond 16 MB, so never embed something that can grow forever.
import mongoose from 'mongoose';
const { Schema, model } = mongoose;
// One user has many posts: store the user's id in each post (a reference).
const userSchema = new Schema({
name: { type: String, required: true, trim: true, minlength: 2 },
email: { type: String, required: true, lowercase: true, unique: true },
});
const postSchema = new Schema(
{
title: { type: String, required: true, trim: true, maxlength: 120 },
body: { type: String, required: true },
author: { type: Schema.Types.ObjectId, ref: 'User', required: true },
tags: [{ type: String, lowercase: true, trim: true }],
status: { type: String, enum: ['draft', 'published'], default: 'draft' },
},
{ timestamps: true },
);
// Indexes make the queries you run often fast. Match them to your real queries.
postSchema.index({ author: 1, createdAt: -1 }); // "my posts, newest first"
postSchema.index({ status: 1, tags: 1 }); // "published posts with this tag"
postSchema.index({ title: 'text', body: 'text' }); // text search
export const User = model('User', userSchema);
export const Post = model('Post', postSchema);
// With a database connection you would write:
// const post = await Post.findById(id).populate('author', 'name email'); // replaces the id by the user
// const mine = await Post.find({ author: userId }).sort({ createdAt: -1 }).limit(10).lean();
The author field of a post is an ObjectId that points at a User. With a connection you replace it by the real user using populate, as shown in the comment at the bottom: Post.findById(id).populate('author', 'name email'). Populate runs a second query behind the scenes, so use it on purpose, ask only for the fields you need, and avoid it inside loops. Use .lean() for read-only lists; it returns plain objects and skips Mongoose's extra work, which is faster.
Validation in the schema
The schema is also your first line of validation. The post requires a title of at most 120 characters, trims spaces, lowercases tags, limits status to two words with enum, and fills in a default. The next file runs those rules without a database, since validation happens in memory, and prints the result.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Install what the lesson needs:
npm install mongoose. - Save both files and run
node db24-check.js. No database is needed for this check.
// Checks the schemas without needing a database: validation and index definitions run in memory.
import { Post, User } from './db24-models.js';
const bad = new Post({ title: '', body: 'x', tags: [' JS ', 'Node'] });
const problems = await bad.validate().catch((error) => error);
console.log('Errors on:', Object.keys(problems.errors).sort()); // title and author are missing
console.log('Tags cleaned:', bad.tags);
console.log('Default status:', bad.status);
const user = new User({ name: 'A', email: 'ASHA@Example.com' });
const userProblems = await user.validate().catch((error) => error);
console.log('User errors on:', Object.keys(userProblems.errors));
console.log('Email lowercased:', user.email);
console.log('Post indexes:', Post.schema.indexes().map(([fields]) => Object.keys(fields).join('+')));
Errors on: [ 'author', 'title' ]
Tags cleaned: [ 'js', 'node' ]
Default status: draft
User errors on: [ 'name' ]
Email lowercased: asha@example.com
Post indexes: [ 'author+createdAt', 'status+tags', 'title+body' ]
Indexes: the biggest speed-up you can buy
Without an index, MongoDB reads every document to answer a query, which is called a collection scan. That is fine for 500 documents and painful for 5 million. An index is a sorted lookup structure on one or more fields. The three indexes in the example match three real questions: *my posts, newest first* uses author and createdAt; *published posts with a tag* uses status and tags; and *search the text* uses a text index. The order of fields in a compound index matters, because it can only be used from the left. An index on { author: 1, createdAt: -1 } helps a query on author alone, but not one on createdAt alone.
- Create indexes for the queries you actually run, not for every field.
- Every index makes writes a little slower and uses memory and disk.
- Use
unique: truefor values that must not repeat, such as an email. It is enforced by an index. - Use
explain()in the shell, or the Atlas performance tools, to confirm that a query uses its index.
A word about MongoDB Atlas
MongoDB Atlas is the hosted service from the makers of MongoDB. It has a free tier that is enough for learning. You create a cluster, add your server's IP address to the access list, create a database user, and copy the connection string into an environment variable such as MONGODB_URI. Never write that string in your code. Atlas clusters are replica sets, which is why transactions work there, as the next lesson shows.
Your task
- Add a
Commentmodel that references both a post and a user, with an index forpostandcreatedAt. - Add a
slugfield toPostwithunique: trueand see how the index list changes. - Write down one thing that you would embed and one that you would reference in your own project, and say why.
How to check it worked
- The check prints the same six lines.
- You can explain embed versus reference using the 16 MB limit.
- You can explain why
{ author, createdAt }does not help a query oncreatedAtalone.