Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Validation and Middleware

Mongoose Custom Validators and Async Validation

Write custom Mongoose validators: sync and async validate functions, cross-field checks, validators on updates, and clean error handling patterns.

Built-in validators cover the common cases. Real applications also have rules that no library can guess: a password must contain a digit, an end date must follow a start date, a username must not be on a reserved list, a coupon must exist in another collection. For these you write a custom validator. This lesson shows how, including asynchronous checks and the gotchas of validating during updates.

The validate option

A validator is a function that returns true for valid values and false for invalid ones. Attach it with the validate option, either with a message in an object or as a function:

JavaScript
const userSchema = new mongoose.Schema({
  password: {
    type: String,
    required: true,
    validate: {
      validator: (v) => /\d/.test(v) && v.length >= 8,
      message: 'Password needs 8+ characters and at least one digit',
    },
  },
  phone: {
    type: String,
    validate: {
      validator: (v) => /^\+?[0-9 ()-]{7,20}$/.test(v),
      message: (props) => `${props.value} is not a valid phone number`,
    },
  },
});

The message can be a function that receives props with value, path, reason and validator. Custom validators run only when the value is not undefined, so required handles missing values and the validator handles the content. The validator receives the value as it is after casting and setters.

You can give a field several validators using an array:

JavaScript
username: {
  type: String,
  validate: [
    { validator: (v) => v.length >= 3, message: 'Too short' },
    { validator: (v) => !['admin', 'root'].includes(v), message: 'Reserved name' },
  ],
}

If the validator throws an error, that error message is used as the validation message.

Cross-field validation

Inside a regular function, this is the document, so you can compare fields:

JavaScript
const bookingSchema = new mongoose.Schema({
  start: { type: Date, required: true },
  end: {
    type: Date,
    required: true,
    validate: {
      validator: function (value) {
        return value > this.start;
      },
      message: 'End must be after start',
    },
  },
});

Arrow functions do not get this, so use function here. If the rule involves several fields and does not belong to one, put it in a pre('validate') hook instead (see Document middleware).

Node.js Custom and cross-field validators (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.

Async validators

A validator can return a promise, which lets you query the database or call a service. This is the right place for a "does this exist?" check, such as confirming a referenced document is real:

JavaScript
const postSchema = new mongoose.Schema({
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    validate: {
      validator: async (id) => (await User.exists({ _id: id })) !== null,
      message: 'Author does not exist',
    },
  },
});

Use async validators sparingly: they add a database round trip on every save and have the same race condition as any check-then-write (the author could be deleted right after). For uniqueness the index is still the right tool.

Mongoose waits for all validators, sync and async, before it decides.

Node.js An async validator (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.

Validators that run on updates

Remember that updateOne and friends skip validation unless you pass runValidators: true. When you do, there are two caveats:

  1. Validators run only for the paths in the update (a validator on end does not run if you only update start).
  2. Inside a custom validator, this is the query, not a document, so cross-field checks through this.start do not work. Use context: 'query' and read values with this.get('start'), or just load and save the document when cross-field rules matter.
JavaScript
await Booking.updateOne({ _id }, { end }, { runValidators: true, context: 'query' });

Also, required validators in updates only fail when you explicitly $unset the field or set it to null.

Re-using validators

Put shared validators in one module and reference them from schemas, so each rule has one definition and one message:

JavaScript
// validators.js
export const slugValidator = {
  validator: (v) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(v),
  message: (props) => `"${props.value}" is not a valid slug`,
};

// schema
slug: { type: String, required: true, validate: slugValidator },

For heavy checks (email syntax, phone numbers, URLs), a tested library like validator is usually better than hand-written regular expressions. Install it on your machine with npm install validator and call validator.isEmail(v) in your validator function.

Handling errors in layers

A clean pattern is to convert Mongoose errors into one application error format in a single place, for example Express error-handling middleware:

JavaScript
export function errorHandler(err, req, res, next) {
  if (err.name === 'ValidationError') {
    const fields = Object.fromEntries(Object.entries(err.errors).map(([k, e]) => [k, e.message]));
    return res.status(400).json({ message: 'Validation failed', fields });
  }
  if (err.name === 'CastError') {
    return res.status(400).json({ message: `Invalid ${err.path}: ${err.value}` });
  }
  if (err.code === 11000) {
    return res.status(409).json({ message: 'Duplicate value', fields: err.keyValue });
  }
  res.status(500).json({ message: 'Server error' });
}

That one function means individual routes stay short and every client sees the same shapes.

Node.js One error handler for three error kinds (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.

Common mistakes

  • Using arrow functions where this is needed.
  • Expecting a validator to run on undefined (use required).
  • Returning nothing from a validator (that counts as falsy and fails).
  • Relying on async "exists" checks for uniqueness.
  • Forgetting that update validators get a query as this.
  • Writing the regular expression in a way that can be slow on long input (catastrophic backtracking).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What should a custom validator function return for a valid value?

    A validator returns true when the value is valid and false when it is not (or a promise resolving to that).
  2. 2. Why use a regular function rather than an arrow function for a cross-field validator?

    Arrow functions ignore the this that Mongoose supplies, so this.start would be undefined.
  3. 3. When a validator runs during an update with runValidators: true, what is this?

    Update validators have no document, so this refers to the query; use this.get('field') with context: 'query'.
  4. 4. When does a custom validator run?

    Custom validators skip undefined values. Use required for presence checks.

Summary

  • Use validate: { validator, message } for custom rules; the validator returns true for valid values.
  • Regular functions get this as the document for cross-field checks; async validators can query other collections.
  • Validators run only for defined values; update validators need runValidators: true and receive a query as this.
  • Centralize error handling to map ValidationError, CastError and duplicate key errors to consistent responses.

Next: Document middleware