Never trust data from the client. Users make typos, and attackers send garbage on purpose. In this chapter you'll protect DevTinder's database in layers: schema validation with Mongoose, sanitization that cleans values, API-level checks that decide which fields may change, and the validator library for emails, URLs and passwords.
In this chapter you'll learn
- the difference between validation and sanitization
- Mongoose's built-in rules:
required,minLength/maxLength,min/max,enum,default,lowercase,trim - custom
validate()functions, andtimestamps - why
uniqueis not a validator - why validators don't run on updates by default
- API-level validation with an allow-list of updatable fields
- the validator.js library:
isEmail,isURL,isStrongPassword
Before you start: read Chapter S2 06: Database, Schema, Models & Mongoose (schemas) and Chapter S2 07: Diving into APIs (the APIs you're protecting).
Validation vs sanitization
- Validation checks whether data is acceptable, and rejects it if not: "age must be at least 18".
- Sanitization cleans data into a standard form: "remove spaces around the email and make it lowercase".
You need both. Sanitization makes " Akshay@Gmail.COM " and "akshay@gmail.com" the same value; validation then checks it's a real email.
Schema-level validation with Mongoose
Here's DevTinder's user schema with all the rules. Each one is explained below.
// src/models/user.js
const mongoose = require("mongoose");
const validator = require("validator");
const userSchema = new mongoose.Schema(
{
firstName: {
type: String,
required: true,
minLength: 3,
maxLength: 50,
trim: true,
},
lastName: {
type: String,
trim: true,
},
emailId: {
type: String,
required: true,
unique: true, // creates a unique INDEX (see below)
lowercase: true,
trim: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error("Invalid email address: " + value);
}
},
},
password: {
type: String,
required: true,
},
age: {
type: Number,
min: 18,
},
gender: {
type: String,
enum: {
values: ["male", "female", "others"],
message: "{VALUE} is not a valid gender",
},
},
photoUrl: {
type: String,
default: "https://geographyandyou.com/images/user-profile.png",
validate(value) {
if (!validator.isURL(value)) {
throw new Error("Invalid photo URL: " + value);
}
},
},
about: {
type: String,
default: "This is a default about of the user!",
},
skills: {
type: [String],
},
},
{ timestamps: true }
);
module.exports = mongoose.model("User", userSchema);// src/models/user.js
const mongoose = require("mongoose");
const validator = require("validator");
const userSchema = new mongoose.Schema(
{
firstName: {
type: String,
required: true,
minLength: 3,
maxLength: 50,
trim: true,
},
lastName: {
type: String,
trim: true,
},
emailId: {
type: String,
required: true,
unique: true, // creates a unique INDEX (see below)
lowercase: true,
trim: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error("Invalid email address: " + value);
}
},
},
password: {
type: String,
required: true,
},
age: {
type: Number,
min: 18,
},
gender: {
type: String,
enum: {
values: ["male", "female", "others"],
message: "{VALUE} is not a valid gender",
},
},
photoUrl: {
type: String,
default: "https://geographyandyou.com/images/user-profile.png",
validate(value) {
if (!validator.isURL(value)) {
throw new Error("Invalid photo URL: " + value);
}
},
},
about: {
type: String,
default: "This is a default about of the user!",
},
skills: {
type: [String],
},
},
{ timestamps: true }
);
module.exports = mongoose.model("User", userSchema);The rules
| Option | Works on | What it does |
|---|---|---|
required: true | any type | the field must be present (and not empty for strings) |
minLength / maxLength | String | length limits |
min / max | Number, Date | value limits |
enum | String, Number | value must be one of a fixed list |
default | any type | value used when none is given |
lowercase / uppercase | String | sanitizer: converts the case before saving |
trim | String | sanitizer: removes spaces at both ends |
validate(value) | any type | your own check; throw to reject |
timestamps: true | schema option | adds createdAt and updatedAt, kept up to date automatically |
We ran this schema against bad input on Mongoose 9. For:
new User({ firstName: " Ak ", emailId: " AKSHAY@Gmail.COM ", age: 15, gender: "Male" });new User({ firstName: " Ak ", emailId: " AKSHAY@Gmail.COM ", age: 15, gender: "Male" });Mongoose first sanitized the values (firstName became "Ak", emailId became "akshay@gmail.com", about got its default, and skills started as an empty array []), then validation failed with:
firstName → Path `firstName` (`Ak`, length 2) is shorter than the minimum allowed length (3).
age → Path `age` (15) is less than minimum allowed value (18).
gender → Male is not a valid genderfirstName → Path `firstName` (`Ak`, length 2) is shorter than the minimum allowed length (3).
age → Path `age` (15) is less than minimum allowed value (18).
gender → Male is not a valid genderTwo things to learn from this:
- Sanitizers run before validators.
" Ak "was trimmed to"Ak"first, so the length check saw 2 characters. enumis case-sensitive."Male"is rejected because the list has"male". Addlowercase: trueto the field if you want to accept any capitalization.
Spell option names exactly. The original course code writes maxLenght (with the letters swapped). Mongoose silently ignores options it doesn't recognize, so that field has no maximum length at all, with no error anywhere. We tested it: maxLength: 5 rejects "abcdefgh", while maxLenght: 3 accepts it.
Custom validators with validate
For rules Mongoose doesn't have, write a function. throw an error to reject the value:
age: {
type: Number,
validate(value) {
if (!Number.isInteger(value)) {
throw new Error("Age must be a whole number");
}
},
},age: {
type: Number,
validate(value) {
if (!Number.isInteger(value)) {
throw new Error("Age must be a whole number");
}
},
},For a fixed list of values, prefer enum over a custom function (as gender does above): it's shorter, and the error message is cleaner.
unique is not a validator
unique: true looks like the other rules, but it works completely differently:
- It tells Mongoose to create a unique index in MongoDB when the app starts (Chapter S2 12: Logical DB Query and Compound Indexes explains indexes).
- The database enforces it: a duplicate insert fails with
E11000 duplicate key error, a MongoDB error witherr.code === 11000, not a MongooseValidationError.
Consequences:
- If the collection already contains duplicates, the index can't be created, and duplicates keep getting in.
- Your error handling has to recognise duplicates separately:
try {
await user.save();
} catch (err) {
if (err.code === 11000) {
return res.status(409).send("Email already registered");
}
res.status(400).send("ERROR: " + err.message);
}try {
await user.save();
} catch (err) {
if (err.code === 11000) {
return res.status(409).send("Email already registered");
}
res.status(400).send("ERROR: " + err.message);
}Validators don't run on updates (by default)
Everything above runs when you call save() or create(). It is skipped for query updates like updateOne, updateMany and findByIdAndUpdate, unless you pass runValidators: true:
await User.findByIdAndUpdate(userId, req.body, {
returnDocument: "after",
runValidators: true, // without this, age: 3 would be saved
});await User.findByIdAndUpdate(userId, req.body, {
returnDocument: "after",
runValidators: true, // without this, age: 3 would be saved
});Even with runValidators, update validators only check the fields in the update, and inside a custom validate() function, this is not the document. In Chapter S2 11: Diving into the APIs and Express router the profile-edit API avoids this problem by changing the fields on the loaded document and calling save(), which runs every validator normally.
API-level validation
Schema rules protect what is stored. API-level checks protect who can change what. Right now, PATCH /user/:userId lets a client change emailId and password, which should go through separate, careful flows.
Use an allow-list: the fields this endpoint may update.
app.patch("/user/:userId", async (req, res) => {
const data = req.body;
try {
const ALLOWED_UPDATES = ["photoUrl", "about", "gender", "age", "skills"];
const isUpdateAllowed = Object.keys(data).every((key) =>
ALLOWED_UPDATES.includes(key)
);
if (!isUpdateAllowed) {
throw new Error("Update not allowed");
}
if (data.skills && data.skills.length > 10) {
throw new Error("You can add at most 10 skills");
}
const user = await User.findByIdAndUpdate(req.params.userId, data, {
returnDocument: "after",
runValidators: true,
});
res.send(user);
} catch (err) {
res.status(400).send("UPDATE FAILED: " + err.message);
}
});app.patch("/user/:userId", async (req, res) => {
const data = req.body;
try {
const ALLOWED_UPDATES = ["photoUrl", "about", "gender", "age", "skills"];
const isUpdateAllowed = Object.keys(data).every((key) =>
ALLOWED_UPDATES.includes(key)
);
if (!isUpdateAllowed) {
throw new Error("Update not allowed");
}
if (data.skills && data.skills.length > 10) {
throw new Error("You can add at most 10 skills");
}
const user = await User.findByIdAndUpdate(req.params.userId, data, {
returnDocument: "after",
runValidators: true,
});
res.send(user);
} catch (err) {
res.status(400).send("UPDATE FAILED: " + err.message);
}
});Object.keys(data)lists the fields the client sent..every(...)istrueonly if every one of them is in the allow-list.- Extra rules that don't belong in the schema (like "max 10 skills per request") also go here.
validator.js: ready-made checks
Writing a correct email or URL check yourself is surprisingly hard. The validator library has dozens of tested functions:
npm install validatornpm install validatorconst validator = require("validator");
validator.isEmail("akshay@gmail.com"); // true
validator.isURL("https://example.com/me.png"); // true
validator.isStrongPassword("Akshay@123"); // true
validator.isStrongPassword("akshay123"); // false: no uppercase letter, no symbolconst validator = require("validator");
validator.isEmail("akshay@gmail.com"); // true
validator.isURL("https://example.com/me.png"); // true
validator.isStrongPassword("Akshay@123"); // true
validator.isStrongPassword("akshay123"); // false: no uppercase letter, no symbolisStrongPassword requires by default: at least 8 characters, with at least 1 lowercase letter, 1 uppercase letter, 1 number and 1 symbol. You can change these: validator.isStrongPassword(pw, { minLength: 10 }).
In Chapter S2 09: Encrypting Passwords you'll use these checks in a validateSignupData helper that runs before the password is hashed.
Never put the password in an error message. Code like throw new Error("Enter a strong password: " + value) copies the user's password into the error, and errors usually end up in log files and often in the API response. Describe the rule instead: "Password must be 8+ characters with upper, lower, number and symbol".
Layers of defence
Common mistakes
- Misspelled options (
maxLenght,minlenght): silently ignored. - Expecting
uniqueto give aValidationError: it's a database error,code 11000. - No
runValidators: trueonfindByIdAndUpdate: invalid updates are saved. - Case-sensitive
enumwithoutlowercase: true:"Male"is rejected. - Echoing passwords (or other secrets) in error messages.
- Only validating in the frontend: anyone can call the API directly with Postman.
Key takeaways
- Validation rejects bad data; sanitization cleans it (
trim,lowercase). Sanitizers run first. - Mongoose rules:
required,minLength/maxLength,min/max,enum,default, customvalidate(), plustimestamps. uniquecreates an index; duplicates fail in MongoDB with E11000 (err.code === 11000).- Validators run on
save()/create(), but on query updates only withrunValidators: true. - Use an allow-list at the API level to control which fields each endpoint may change.
- Use validator.js for emails, URLs and strong passwords, and never echo passwords in errors.
Interview questions
Q1. What is the difference between validation and sanitization?
Validation checks whether input meets the rules and rejects it if not (email format, minimum age). Sanitization transforms input into a safe, standard form (trimming spaces, lowercasing emails, escaping HTML). Sanitize first so validation works on normalized values, and always do both on the server.
Q2. Is unique: true a validator in Mongoose?
No. It's a shortcut for creating a unique index in MongoDB. The database enforces it, so a duplicate causes an E11000 duplicate key error (code 11000), not a Mongoose ValidationError. If duplicates already exist when the index is built, the index creation fails and uniqueness isn't enforced.
Q3. Why don't Mongoose validators run on findByIdAndUpdate?
Query updates send an update command straight to MongoDB without loading the document, so Mongoose's document validation doesn't run by default. Pass { runValidators: true } to run validators on the fields being updated, or load the document, modify it and call save(), which runs full validation.
Q4. What does timestamps: true do?
It adds createdAt and updatedAt fields to the schema. Mongoose sets both when a document is created, and updates updatedAt on every save and query update. The field names can be customized: { timestamps: { createdAt: 'created_at' } }.
Q5. Should you validate on the frontend, the backend or both?
Both, but the backend is mandatory. Frontend validation improves the user experience (instant feedback), but anyone can bypass it by calling the API directly. Backend validation is the real protection, and the database (unique indexes, schema validation) is the last line of defence.
Q6. How would you restrict which fields a user can update?
Use an allow-list: define the updatable fields for that endpoint, check Object.keys(req.body).every(k => allowed.includes(k)), and reject the request otherwise. Alternatively, copy only allowed fields into a new object. Sensitive fields like email, password or roles get their own dedicated endpoints.
Q7. How do you write a custom validator in Mongoose?
Add a validate function (or validate: { validator: fn, message: "..." }) to the field. Return false or throw an error to reject the value. For example, validate(v) { if (!validator.isEmail(v)) throw new Error("Invalid email") }. Async validators can return a Promise.
What's next
The user schema is solid, but passwords are still stored as plain text, so anyone who sees the database sees every password. In Chapter S2 09: Encrypting Passwords you'll hash passwords with bcrypt and build a proper login.