In the previous parts of this series, we created a MongoDB database and started adding documents into collections. But as your data grows, it’s important to make sure it stays clean, consistent, and structured. This is where validation rules come in.

In this article, you’ll learn:

  • What validation rules are in MongoDB
  • Why they’re useful
  • How to apply them
  • How to manage them visually with DbSchema

What Are Validation Rules?

Validation rules in MongoDB allow you to enforce structure within your collections. They help prevent documents with missing or incorrect fields from being inserted or updated.

MongoDB uses JSON Schema to define these rules.


Why Use Validation Rules?

  • Prevent mistakes – Stop invalid data before it’s saved
  • Keep structure consistent – Make sure all documents follow your expected layout
  • Support clean application logic – Fewer errors, clearer expectations

Example: Apply Validation Rules to the passengers collection:

  • Passengers Collection – Name Field

    Ensure the name field is always stored as a string, not mistakenly saved as a number or other type.

  • Passengers Collection – Destination Field

    Make sure the destination value matches a valid city or airport name from a predefined list to avoid typos.

  • Passengers Collection – Age Field

    Validate that the age is always a positive number, preventing incorrect or negative values during data entry.

We can apply the following validation:

db.createCollection("passengers", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "age", "destination"],
      properties: {
        name: {
          bsonType: "string",
          description: "must be a string and is required"
        },
        age: {
          bsonType: "int",
          minimum: 0,
          description: "must be a non-negative integer"
        },
        destination: {
          bsonType: "string",
          description: "must be a string and is required"
        }
      }
    }
  },
  validationLevel: "strict",
  validationAction: "error"
})

What does this mean?

required: Specifies which fields must be present

bsonType: Defines the expected type for each field

validationLevel: strict: MongoDB will validate every insert/update

validationAction: error: Invalid operations will be blocked

Check Validation Rules

db.runCommand({ listCollections: 1, filter: { name: "passengers" } })

Test it

db.passengers.insertOne({ name: "Jennifer", age: 30 })

Since destination is required, this will throw a validation error!

Setting Up Validation Rules in DbSchema

If you’re using DbSchema, you can define and manage validation rules visually - no need to write complex JSON manually.

How to Set Up Validation in DbSchema:

When creating the passengers collection in DbSchema with validation rules, you’ll need to define the following fields:

Field Name Data Type Mandatory Notes
_id ObjectId Optional Usually auto-generated by MongoDB
name String Yes Set Mandatory = true
age Integer Yes Set Mandatory = true, minimum value can be noted
destination String Yes Set Mandatory = true

How to Add These in DbSchema:

  1. Right-click on the diagram and choose "Create Validator / Define Collection".
  2. Click "Add" to enter each field above.
  3. Select the correct Data Type for each.
  4. Check the "Mandatory" box where required.

Create Visually a Validation Rule using DbSchema

  1. Choose the validation level and action.

Set Validation Level Visually a Validation Rule using DbSchema

  1. Click OK to apply the validation rules.

Collections with validation rules in DbSchema are shown as non-virtual, while collections without validation rules are marked as virtual.

Symbols of Validation Rule using DbSchema

These settings help you build structure into your schema visually. However, advanced JSON Schema options (like minimum, pattern, or complex nested validations) are not available through the GUI. For those, you may need to use the shell or script editor manually.

Next Chapter

How Collections Connect – Relationships in MongoDB

  • While MongoDB doesn’t use joins like relational databases, you can still represent relationships using embedded documents or references. We’ll explore when to embed, when to reference, and how tools like DbSchema help you visualize those connections clearly.

Next Lesson