MongoDB's schema validation guarantees that documents inserted into a collection fulfill the user-defined requirements or constraints. This feature contributes to data integrity and consistency inside the database.
When Should You Use Schema Validation?
When you understand your application's structure and data requirements, use schema validation.
Avoid schema validation during the testing phase of a new application, especially if the incoming data is unpredictable and the structure is unclear.
Use schema validation to impose rules on specific fields, hence assuring data consistency and integrity.
For example, in a collection that stores usernames as strings, schema validation might prohibit usernames from being stored with other data types, hence maintaining data homogeneity.
Schema validation ensures data quality by enforcing criteria such as data types, sizes, and formats, which improves database reliability and consistency.
When does MongoDB validate data?
MongoDB applies schema validation to changes and inserts in collections.
Only new documents that are inserted into pre-existing, non-empty collections with validation rules are validated.
Existing documents in a collection are not validated until they have been changed.
Use the 'collMod' command to modify existing schema validation rules.
MongoDB ensures data integrity through validation while also providing flexibility for handling existing data.
Validation Rules
When creating or modifying a collection, use the validator option to provide validation requirements.
The validator option specifies a query phrase that validates documents as they are added or changed to the collection.
The validation criteria can be defined using MongoDB query operators and expressions.
Validation Actions
Validation actions specify what action to perform when a document violates the validation rules. The actions can be error, warn, or off.
Error: The document failed validation and will not be inserted or changed.
Warn: The document will be inserted or changed, but a warning will be issued.
Off: No validation will occur.
Implementation of Schema Validation
JSON Schema Validation: Sets validation criteria with the $jsonSchema operator.
On Collection Creation: When creating a collection, use the validator option along with the database.createCollection().
On Existing Collections: On existing collections, use the collMod command together with the validator option.
Validation Levels
Strict (default): Validate all inserts and updates.
Moderate: Validates inserts and modifications to documents that currently adhere to the schema.
Benefits of Schema Validation
Prevents unexpected data types: Prevents invalid data from entering the collection (for example, password as an image).
Ensures data integrity: Protects against accidental errors during data entry.
Enforces data standards: Ensures a well-defined data model in your application.