While MongoDB collections can be created implicitly upon document insertion, explicit collection creation via db.createCollection() allows setting collection options like JSON Schema Validation, capped sizes, and collation rules.
flowchart TD
A["db.createCollection('users', validatorOptions)"] --> B["MongoDB Schema Validation Engine"]
B --> C["Document Insert Request"]
C -->|"Matches JSON Schema"| D["Document Saved to Storage"]
C -->|"Fails Validation Rules"| E["Rejection Exception (DocumentValidationFailure)"]
import { MongoClient } from 'mongodb';
const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);
async function createValidatedCollection() {
try {
await client.connect();
const db = client.db('kodersolution_no_sql');
// Define JSON Schema Validation Rules
const collectionOptions = {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['name', 'email', 'role'],
properties: {
name: {
bsonType: 'string',
description: 'name must be a non-empty string'
},
email: {
bsonType: 'string',
pattern: '^.+@.+$',
description: 'email must match valid email string pattern'
},
role: {
enum: ['admin', 'developer', 'viewer'],
description: 'role must be one of predefined enum values'
}
}
}
}
};
const collection = await db.createCollection('members', collectionOptions);
console.log('Collection [members] created with strict JSON Schema validation rules!');
} catch (error) {
console.error('Collection Creation Error:', error.message);
} finally {
await client.close();
}
}
createValidatedCollection();
$jsonSchema rules when creating collections to enforce data integrity at database level without relying solely on application ODM logic.capped: true, size: 5242880) for high-speed logging or audit tails where oldest entries auto-expire.db.listCollections() before createCollection() to avoid throwing error code 48 (NamespaceExists).What is a capped collection in MongoDB, and what is its primary production use case?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With