Loading lessons...
Schema Validation
Schema Validation
By default MongoDB has a flexible schema - documents in a collection can have different fields and types. Sometimes you want to enforce structure, and that's what schema validation is for.
$jsonSchema
MongoDB uses the $jsonSchema operator to define validation rules. You pass it to db.createCollection() in the validator option:
db.createCollection("posts", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "title", "body" ],
properties: {
title: { bsonType: "string", description: "Title of post - Required." },
body: { bsonType: "string", description: "Body of post - Required." },
category: { bsonType: "string", description: "Category of post - Optional." },
likes: { bsonType: "int", description: "Post like count. Must be an integer - Optional." },
tags: { bsonType: ["string"], description: "Must be an array of strings - Optional." },
date: { bsonType: "date", description: "Must be a date - Optional." }
}
}
}
})
The keywords
bsonType: enforces the data type of a field (string, int, date, etc.).required: lists fields that MUST be present.properties: describes the rules for each field.description: human-readable notes about the field.
When validation runs
Validation runs on insert and update operations. By default, invalid documents are rejected (validationAction: "error").
TL;DR
- Flexible schema by default; validation makes it strict.
$jsonSchemadefines rules withbsonType,required,properties.- Set up with
db.createCollection(name, { validator: {...} }).