Mongoose schemas, validation and population
Build a Node HTTP API from scratch, model data in SQL and MongoDB, and reason about transactions, indexes, caching and authentication so the endpoint you ship stays correct under load.
What you will be able to do
#- Define a Mongoose schema with validation and defaults.
- Use populate to resolve references and explain its cost.
- Choose lean() for read-only queries.
Overview
#Mongoose adds a schema layer over the MongoDB driver: typed paths, built-in validators, middleware and helpers like populate.
A schema with validation
const mongoose = require('mongoose');
const articleSchema = new mongoose.Schema({
title: { type: String, required: true, minlength: 3, trim: true },
status: { type: String, enum: ['draft', 'published'], default: 'draft' },
author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author', required: true },
}, { timestamps: true });
const Article = mongoose.model('Article', articleSchema);
Populate
populate replaces a stored id with the referenced document. It runs a separate query, so populating in a loop recreates N plus one.
const articles = await Article.find({ status: 'published' }).populate('author').limit(20);
lean()
By default Mongoose returns hydrated documents with getters, setters and methods. For read-only responses, .lean() returns plain objects and skips that overhead.
Common pitfalls
- Calling
populateinside a loop instead of once on the query. - Relying on schema validation alone when updates use
updateOnewithrunValidatorsoff by default. - Forgetting that
findreturns a query you mustawaitor execute.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Define a Mongoose schema for a comment with a required body, a required article reference and a default createdAt.
starter.javascript// const commentSchema = new mongoose.Schema({ ... })Reveal the reference answer
reference.javascriptconst commentSchema = new mongoose.Schema({ body: { type: String, required: true, trim: true }, article: { type: mongoose.Schema.Types.ObjectId, ref: 'Article', required: true }, createdAt: { type: Date, default: Date.now }, });Authored expected output: A schema with body required, article an ObjectId ref required, and createdAt defaulting to now.
Required paths reject missing data, ref enables populate, and a default fills createdAt when the document is created.
Exercise 2Debug
This loop is slow on 100 articles. Explain why and fix it.
starter.javascriptconst articles = await Article.find().limit(100); for (const a of articles) { await a.populate('author'); }Reveal the reference answer
reference.javascriptconst articles = await Article.find().populate('author').limit(100);Authored expected output: One populate query instead of 100.
populate inside the loop issues one query per document. Calling populate on the query resolves all references in a single additional query.
Common misconceptions
#- Mongoose validation runs on every update: update operations do not run validators unless you enable runValidators.
- populate is a join: it issues an additional query and does not exist server-side.
Follow-up practice
#- backend-databases-integrity
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.