Schema Validation in MongoDB
Introduction
Welcome back to our journey through MongoDB. In our last few lessons, we've explored various data types supported by MongoDB and tackled different types of relations: one-to-one, one-to-many, and many-to-many. Now, we'll be adding another tool to our toolkit: Schema Validation. Validation is a way for us to enforce certain rules and standards on our data, ensuring that all entries in our database meet certain requirements.
Structuring Documents
As mentioned earlier, MongoDB is schemaless, which means that a single collection can store documents with entirely different structures. For example:
Although this is technically possible, developers typically ensure that all documents in a collection share a similar structure or at least have consistent core fields to avoid complications in querying and data integrity. For instance:
In this example, while title, author, and published_year are the core fields required for each document, several optional fields like genre, copies_sold, cover_type, language, and pages are also included. These optional fields provide additional information but aren't mandatory for each document. To enforce the required fields and maintain consistency, we can use Schema Validation.
Schema Validation in MongoDB
Schema validation allows us to define specific rules that all documents in a collection must follow. These rules can range from simple—such as requiring a field to be a string—to complex, like ensuring a numerical field falls within a certain range. By implementing validation, we ensure data integrity and consistency across our collections.
MongoDB provides two important options for fine-tuning schema validation: validationLevel and validationAction.
The validationLevel option specifies which documents should undergo validation:
strict: This is the default setting. All documents must comply with the validation rules, including those already in the collection and any newly inserted or updated documents.moderate: This setting enforces validation only during updates or insertions. Existing documents that do not conform to the rules will not cause errors unless they are modified.
The validationAction option specifies what should happen when validation fails:
error: This is the default setting. Any document that does not meet the validation rules will cause the insertion or update operation to fail with an error.warn: Instead of causing an error, the operation will proceed, but a warning will be logged. This can be useful for tracking validation rule violations without rejecting data.
You can specify these options when creating or modifying a collection with schema validation.
