Untitled Lesson
Skill Matrix
UNLOCK NODES BY LEARNING NEW TAGS.
A login endpoint queries `User.findOne({ username, password: req.body.password })` without validating that password is a string. What can an attacker send to bypass authentication?
💻 Code Challenge | +75 XP
Add a Zod schema validating that a login request's username and password are both strings (not objects), and apply express-mongo-sanitize as an additional defense-in-depth middleware.
A security audit found a MongoDB-backed login endpoint is vulnerable to a $ne operator injection bypass. Reorder the steps to fix it with layered defenses.
Task: Reorder the blocks in logical sequence to solve the problem.
A.D.A. Interface
Adaptive Didactic Assistant

Pascual Vila
Frontend Instructor // Code Syllabus
The Error //
Passing req.body values directly into a MongoDB query filter without type validation
// Wrong: password could be an object with a MongoDB operator
User.findOne({ username, password: req.body.password });
// Correct: validated as a string first
const { password } = loginSchema.parse(req.body); // Zod rejects non-strings
User.findOne({ username, password });The Solution //
A JSON request body can contain a nested object anywhere a plain string was expected, and MongoDB's query language interprets certain nested object shapes (like { "$ne": null }) as operators rather than literal values — bypassing authentication or filtering logic entirely if the value isn't validated as a primitive type first.
The Error //
Relying solely on Mongoose schema type casting to prevent operator injection
// Insufficient alone
const UserSchema = new Schema({ password: { type: String } });
// Add explicit validation as the primary defense
const { password } = loginSchema.parse(req.body);The Solution //
Mongoose's automatic type casting behavior for query filters is inconsistent across query methods and versions and was never designed as a security feature — it should never be the only defense against NoSQL injection. Pair it with explicit input validation and sanitization middleware.