Schema Validation की जानकारी
Validation rules एक flexible schema में भी documents consistent रखते हैं।
In this page:
Syntax
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
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. #}
आम गलतियां
- critical collections के लिए validation skip करना
- evolve करने के लिए बहुत strict rules
- यह मान लेना कि validation existing data check करता है
चैप्टर सारांश
- $jsonSchema rules define करता है
- validationLevel और validationAction इसे tune करते हैं
- collMod बाद में rules बदलता है
- Writes पर apply होता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: