← Back to MongoDB Course | Chapter 9: Schema Design | Lesson 3 of 7

Schema Validation की जानकारी

Validation rules एक flexible schema में भी documents consistent रखते हैं।

In this page:

  1. Schema Validation
Syntax
javascript
db.createCollection("collection_name", {
  validator: { $jsonSchema: {
    bsonType: "object",
    required: ["field"],
    properties: { field: { bsonType: "type" } }
  } }
})

Schema Validation

fields require करने, types restrict करने, और ranges या enums set करने के लिए एक collection validator में $jsonSchema इस्तेमाल करें। validationLevel (strict या moderate) और validationAction (error या warn) से combine करें। अपना model बदलने के साथ collMod से rules evolve करें।

Note: moderate validationLevel update करते वक्त existing invalid documents skip करता है।

उदाहरण: Schema validation

bash
test> db.runCommand({
...   collMod: "users",
...   validator: { $jsonSchema: { bsonType: "object", required: ["email"], properties: { role: { enum: ["user", "admin"] } } } },
...   validationLevel: "moderate", validationAction: "error"
... })
{ ok: 1 }
test> db.users.insertOne({ email: "[email protected]", role: "guest" })
MongoServerError: Document failed validation

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. critical collections के लिए validation skip करना
  2. evolve करने के लिए बहुत strict rules
  3. यह मान लेना कि validation existing data check करता है
चैप्टर सारांश
  • $jsonSchema rules define करता है
  • validationLevel और validationAction इसे tune करते हैं
  • collMod बाद में rules बदलता है
  • Writes पर apply होता है

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.