MongoDB Schema Validation example
Schema Validation in MongoDB allows you to define rules for the structure of documents within a collection. By specifying a schema, you can enforce data consistency and ensure that documents conform to certain constraints. Here’s how you can define schema validation for a MongoDB collection with the keys "title"
, "body"
, "category"
, "links"
, "tags"
, and "date"
.
Example Schema Validation
Suppose you have a collection named posts
, and you want to enforce validation rules on the following fields:
title
: A string that must be present.body
: A string that must be present.category
: A string that must be present and limited to a set of predefined values.links
: An array of strings where each string must be a valid URL.tags
: An array of strings where each string is a tag.date
: A date field that must be a valid ISO date format.
Here’s how you can define schema validation for this structure using MongoDB's JSON Schema validator:
Defining Validation Rules
Create the Collection with Validation Rules: You can create the collection with schema validation rules using the
createCollection
command.db.createCollection("posts", { validator: { $jsonSchema: { bsonType: "object", required: ["title", "body", "category", "date"], // Fields that must be present properties: { title: { bsonType: "string", description: "Title must be a string and is required" }, body: { bsonType: "string", description: "Body must be a string and is required" }, category: { bsonType: "string", enum: ["news", "blog", "article"], // Restrict to these predefined values description: "Category must be one of the specified values and is required" }, links: { bsonType: "array", items: { bsonType: "string", pattern: "^(http|https)://.*$" // Must be a valid URL }, description: "Links must be an array of valid URLs" }, tags: { bsonType: "array", items: { bsonType: "string" }, description: "Tags must be an array of strings" }, date: { bsonType: "date", description: "Date must be a valid ISODate" } } } }, validationAction: "error", // Use "warn" if you want to log warnings instead of errors validationLevel: "strict" // Use "moderate" to allow existing documents not matching the schema });
Update Validation Rules for an Existing Collection: If you need to modify the validation rules for an existing collection, you can use the
collMod
command.db.runCommand({ collMod: "posts", validator: { $jsonSchema: { bsonType: "object", required: ["title", "body", "category", "date"], // Ensure fields are present properties: { title: { bsonType: "string", description: "Title must be a string and is required" }, body: { bsonType: "string", description: "Body must be a string and is required" }, category: { bsonType: "string", enum: ["news", "blog", "article"], // Enforce predefined values description: "Category must be one of the specified values and is required" }, links: { bsonType: "array", items: { bsonType: "string", pattern: "^(http|https)://.*$" // Validate URLs }, description: "Links must be an array of valid URLs" }, tags: { bsonType: "array", items: { bsonType: "string" }, description: "Tags must be an array of strings" }, date: { bsonType: "date", description: "Date must be a valid ISODate" } } } }, validationAction: "error", // Set to "warn" for warnings validationLevel: "strict" // Change to "moderate" if needed });
Key Points of Schema Validation
- Required Fields: The
required
array specifies which fields must be present in the document. - Data Types:
bsonType
specifies the expected data type for each field (e.g.,string
,date
,array
). - Enumerations: The
enum
field restricts the value to a predefined set of options (useful for fields likecategory
). - Pattern Matching: The
pattern
field is used to validate string formats (e.g., ensuring URLs are valid). - Array Validation: You can validate items within an array, such as ensuring that
links
contains only valid URLs. - Validation Actions:
validationAction
can be set toerror
to reject invalid documents orwarn
to log warnings without rejecting them. - Validation Levels:
validationLevel
can bestrict
(enforces schema for all documents) ormoderate
(enforces schema only for new or modified documents).