Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Validation and Middleware

Mongoose Validation: Built-in Validators

Use Mongoose's built-in validators (required, min, max, minlength, enum, match), understand when validation runs, and read ValidationError details.

Validation is the most valuable reason to use Mongoose. A schema does not only describe your data, it also rejects data that breaks the rules. This lesson covers the built-in validators, when validation runs, what the errors look like and how to return them to API clients in a friendly way.

Built-in validators

Validator Applies to Meaning
required all types value must exist (not undefined, null, or, for strings, empty)
min, max Number, Date numeric or date range
minlength, maxlength String length range
enum String, Number value must be in a list
match String must match a regular expression
unique all not a validator, creates an index (see below)
JavaScript
const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: [true, 'Username is required'],
    minlength: [3, 'Username must have at least 3 characters'],
    maxlength: 20,
    match: [/^[a-z0-9_]+$/, 'Use lowercase letters, digits and underscores only'],
  },
  age: { type: Number, min: [13, 'You must be 13 or older'], max: 120 },
  role: {
    type: String,
    enum: { values: ['user', 'editor', 'admin'], message: '{VALUE} is not a valid role' },
    default: 'user',
  },
  birthday: { type: Date, max: Date.now },
});

Every validator accepts either a plain value or a [value, message] array. In a message you can use , , , placeholders.

required in detail

required: true fails for undefined, null and empty strings (''). It does not fail for 0 or false, which are valid values. Required can also be a function, so a field can be required conditionally:

JavaScript
const orderSchema = new mongoose.Schema({
  paymentMethod: String,
  cardLast4: {
    type: String,
    required: function () { return this.paymentMethod === 'card'; },
  },
});

Arrays are a special case: an array field is never undefined (it defaults to []), so required: true on an array checks nothing useful. Validate that case with a custom validator on length.

Validators on arrays and nested data

Validators like enum and min apply to the elements when the array type is declared with options: tags: [{ type: String, enum: ['a', 'b'], lowercase: true }]. Subdocuments are validated with their own schema when the parent is validated, with error paths such as comments.0.text.

unique is not validation

unique: true creates a unique index in MongoDB. It is checked by the database on write, producing a duplicate key error (code 11000), not a ValidationError. Do not expect it to appear in validate() results.

When validation runs

Operation Validates?
doc.save(), Model.create() yes, automatically
doc.validate() yes, explicitly, without saving
Model.insertMany() yes
updateOne, updateMany, findOneAndUpdate no, unless runValidators: true
bulkWrite updates no, unless you opt in
lean() or raw driver writes no

Validation also runs after casting and setters. So ' ADA ' with trim is trimmed first and then checked against minlength.

You can skip validation on one save with doc.save({ validateBeforeSave: false }) or { validateBeforeSave: false } in the schema options, and validate only some paths with doc.validate(['username']).

The shape of a ValidationError

When a document is invalid, Mongoose throws a ValidationError whose errors property maps each bad path to its own ValidatorError (or CastError):

JavaScript
try {
  await User.create({ username: 'A!', age: 5, role: 'boss' });
} catch (err) {
  console.log(err.name);                  // 'ValidationError'
  console.log(Object.keys(err.errors));   // [ 'username', 'age', 'role' ]
  console.log(err.errors.age.message);    // 'You must be 13 or older'
  console.log(err.errors.age.kind);       // 'min'
  console.log(err.errors.age.value);      // 5
}

Each entry has message, kind (the validator type), path and value. Mongoose collects all field errors rather than stopping at the first, so one response can tell the user everything that is wrong.

A stand-in validator

This runnable stand-in is not Mongoose. It implements required, min, max, minlength, enum and match with custom messages and collects every error, like a ValidationError.

Node.js Built-in validators and error collection (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Returning errors to clients

Map the error object to a response that a front end can show next to each form field:

JavaScript
function formatValidationError(err) {
  return Object.fromEntries(
    Object.entries(err.errors).map(([path, e]) => [path, e.message])
  );
}

app.post('/users', async (req, res) => {
  try {
    res.status(201).json(await User.create(req.body));
  } catch (err) {
    if (err.name === 'ValidationError') {
      return res.status(400).json({ errors: formatValidationError(err) });
    }
    throw err;
  }
});

Note that for CastError entries (a string where a number was expected), message is Mongoose's technical text, so you may want to replace it with something friendlier.

Node.js Formatting errors for an API response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Validation is not security by itself

Schema validation protects data quality, but it is not the only line of defense. Validate and sanitize request data at the edge (types, lengths), use strict mode, pick allowed fields, and rely on database indexes for uniqueness. Remember that anything that bypasses Mongoose (another service, the shell) is not validated at all.

Common mistakes

  • Expecting unique: true to produce a ValidationError.
  • Using required: true on an array and thinking it checks for items.
  • Assuming updateOne validates.
  • Believing min works on strings (use minlength).
  • Writing messages only for the first error, when users need to see all of them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which validator should limit the length of a String field?

    min and max apply to numbers and dates; strings use minlength and maxlength.
  2. 2. Does Model.updateOne() run validators by default?

    Update operations skip validation unless runValidators is enabled.
  3. 3. What error does a violated unique index produce?

    unique creates an index. The database rejects the write with error code 11000.
  4. 4. How many field errors does a ValidationError report?

    Mongoose validates every path and collects all problems in the errors object.

Summary

  • Built-in validators: required, min/max, minlength/maxlength, enum, match, each with optional custom messages.
  • Validation runs on save, create, insertMany and validate(); updates need runValidators: true.
  • A ValidationError has an errors map by path with message, kind and value.
  • unique is an index, not a validator; handle error code 11000 separately.

Next: Custom validators and error handling