Data Validation
Data Validation
2. Validation Rules
• Data Types: Specify the data type for fields (e.g., string, number, date).
3. Validation Levels
Setup Steps:
Scenario: Ensure every user document has username, email, and password. The email must be
unique and valid.
Schema:
json
Copy code
"$jsonSchema": {
"bsonType": "object",
"required": ["username", "email", "password"],
"properties": {
"username": {
"bsonType": "string",
},
"email": {
"bsonType": "string",
"pattern": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
},
"password": {
"bsonType": "string",
"minLength": 8,
Create Collection:
javascript
Copy code
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
properties: {
email: {
bsonType: "string",
pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
},
});
Scenario: Ensure all products have a name, price, stock, and optional tags. Price must be positive,
and stock cannot be negative.
Schema:
json
Copy code
"$jsonSchema": {
"bsonType": "object",
"properties": {
"name": {
"bsonType": "string",
},
"price": {
"bsonType": "double",
"minimum": 0,
},
"stock": {
"bsonType": "int",
"minimum": 0,
},
"tags": {
"bsonType": "array",
Scenario: Track employees with name, age, department, and hireDate. The age must be between 18
and 65, and hireDate must be a valid date.
Schema:
json
Copy code
"$jsonSchema": {
"bsonType": "object",
"properties": {
"name": {
"bsonType": "string",
},
"age": {
"bsonType": "int",
"minimum": 18,
"maximum": 65,
"description": "Age must be between 18 and 65"
},
"department": {
"bsonType": "string",
},
"hireDate": {
"bsonType": "date",
Scenario: Store feedback with a rating, comments, and submittedAt. Rating must be between 1 and
5.
Schema:
json
Copy code
"$jsonSchema": {
"bsonType": "object",
"properties": {
"rating": {
"bsonType": "int",
"minimum": 1,
"maximum": 5,
},
"comments": {
"bsonType": "string",
},
"submittedAt": {
"bsonType": "date",
Scenario: Record sensor data with a sensorId, temperature, humidity, and timestamp. Temperature
must be within -50 to 150.
Schema:
json
Copy code
"$jsonSchema": {
"bsonType": "object",
"properties": {
"sensorId": {
"bsonType": "string",
},
"temperature": {
"bsonType": "double",
"minimum": -50,
"maximum": 150,
"description": "Temperature must be between -50 and 150"
},
"humidity": {
"bsonType": "double",
"minimum": 0,
"maximum": 100,
},
"timestamp": {
"bsonType": "date",
Validation in Action
To test validation:
javascript
Copy code
db.users.insertOne({
username: "john_doe",
email: "john@example.com",
password: "password123"
});
javascript
Copy code
db.users.insertOne({
username: "jane_doe",
});
Real-World Benefits