In this lesson, you will learn how to use JSON Schema to enforce strict data types on your documents, ensuring that your database rejects entries that don't match your expected structure.
The Problem of "Schema-on-Read"
One of the hallmarks of NoSQL document stores is flexibility, but this often leads to "data drift," where fields are inconsistently typed—for example, one document stores age as a string ("25") while another stores it as an integer (25). Validation rules act as a gatekeeper, moving your schema enforcement from the application layer directly into the database engine.
Defining Strict Validation
By using JSON Schema, you define an object that acts as a contract. If a write operation attempts to insert or update a document that violates these constraints, the database will throw a validation error.
Consider a user collection where username must be a string and account_balance must be a non-negative number:
{
"$jsonSchema": {
"bsonType": "object",
"required": ["username", "account_balance"],
"properties": {
"username": {
"bsonType": "string",
"description": "must be a string and is required"
},
"account_balance": {
"bsonType": "number",
"minimum": 0,
"description": "must be a number and must be 0 or greater"
}
}
}
}
Why This Matters
When you define these rules, you eliminate the need for your application code to constantly check if fields exist or if they are of the correct type before performing calculations. By enforcing types like bsonType, you protect your downstream analytical processes from failing due to unexpected data formats.
Think of this as a "server-side constraint." Even if a rogue script or a bug in a microservice attempts to push an incorrectly formatted object into your collection, the database engine itself will stop the operation, keeping your data layer pristine.
Key Takeaway: JSON Schema validation rules allow you to move data integrity checks into the database, ensuring that only records with the correct data types are persisted.