Validation के Basics
Schema validation आपको fields और types require करने देता है भले ही MongoDB flexible हो।
In this page:
Syntax
db.createCollection("collection_name", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["field1"],
properties: { field1: { bsonType: "string" } }
}
}
})
Validation Basics
एक collection बनाते वक्त, required fields, types, और value ranges demand करने के लिए $jsonSchema इस्तेमाल करते हुए एक validator add करें। validationAction चुनता है कि invalid writes reject (error) हों या सिर्फ logged (warn) हों।
Existing documents तब तक re-check नहीं होते जब तक ये update न हों।
Note:
enforce करने से पहले यह देखने के लिए कि क्या fail होगा validationAction warn से शुरू करें।
उदाहरण: Validation basics
test> db.createCollection("accounts", {
... validator: { $jsonSchema: {
... bsonType: "object",
... required: ["email", "age"],
... properties: {
... email: { bsonType: "string" },
... age: { bsonType: "int", minimum: 18 }
... }
... } }
... })
{ ok: 1 }
test> db.accounts.insertOne({ email: "[email protected]", age: 15 })
MongoServerError: Document failed validation
test> db.accounts.insertOne({ email: "[email protected]", age: 30 })
{ acknowledged: true, insertedId: ObjectId('65a1b2c3d4e5f60718293a4e') }
⚠️ 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. #}
आम गलतियां
- यह मान लेना कि MongoDB हमेशा एक schema enforce करता है
- यह भूल जाना कि validation सिर्फ writes पर apply होता है
- real data के लिए validators को बहुत strict बनाना
चैप्टर सारांश
- $jsonSchema required fields और types define करता है
- validationAction error या warn है
- Collection creation पर या collMod से set करें
- Inserts और updates पर check होता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: