Practice & Assessment
Test your understanding of Mongoose and Node.js Integration
Multiple Choice Questions
5In a Mongoose pre('save') hook, what does calling next() with an Error argument do?
What is the N+1 query problem with Mongoose populate?
Are Mongoose virtual properties stored in MongoDB?
What is the difference between a Mongoose schema static and an instance method?
In Mongoose, which schema option makes all find queries exclude soft-deleted documents automatically?
Coding Challenges
1User Authentication Schema with Hooks
Build a Mongoose User model with fields: email (required, unique, lowercase), password (required, min 8 chars), role (enum: user/admin, default: user), createdAt (Date, default now). Add: (1) a pre('save') hook that hashes the password with bcrypt only when it is modified. (2) an instance method comparePassword(candidate) that returns a boolean. (3) a static findByEmail(email) method. (4) a virtual fullName that concatenates firstName and lastName (add those fields too). Write a test script that creates a user, logs in by comparing passwords, and prints fullName. Input: hardcoded test user data. Output: login success/failure and fullName. Estimated time: 25 minutes.
Mini Project
Blog REST API with Mongoose
Build a full Express + Mongoose REST API for a blog platform. Models: User (name, email, password, createdAt) and Post (title, body, author ref User, tags array, published boolean, createdAt). Implement: bcrypt password hashing in a pre('save') hook, a virtual slug derived from title, a Post static findPublished() that returns only published posts, and populate author name/email on all post endpoints. Endpoints: POST /auth/register, POST /auth/login (return JWT), GET /posts (public), POST /posts (auth), PATCH /posts/:id (auth, owner only), DELETE /posts/:id (auth, owner only). Validate all inputs. Return 401 for unauthenticated and 403 for unauthorized.
