Intermediate LevelMongoDB & Mongoose
How do JSON Schema validation rules enforce constraints at the MongoDB database level?
❓ Interview Prompt: Explain $jsonSchema database validation, createCollection validator options, validationLevel (strict/moderate), and driver-agnostic enforcement.
MongoDB supports JSON Schema validation rules enforced directly inside the database kernel:
Advantage over Mongoose Validation:
JSON Schema rules reject non-conforming writes at the database layer regardless of which client driver (Node.js, Python, Go) or GUI tool connects!
Code Implementation Example
typescript
import mongoose from 'mongoose';
async function createValidatedUsersCollection() {
const db = mongoose.connection.db;
await db!.createCollection('secure_users', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['name', 'email'],
properties: {
name: { bsonType: 'string' },
email: { pattern: '^.+@.+$', description: 'Must be valid email' }
}
}
},
validationLevel: 'strict',
validationAction: 'error'
});
}💡Defining database-level JSON Schema validation rules in MongoDB.
🎯 Interview Key Takeaway
Use $jsonSchema validation at the database level to enforce schema constraints across all connecting applications.
#$jsonSchema#Database Validation#Schema Enforcement#Intermediate
Back to all MongoDB & Mongoose Questions→