ระดับและการดำเนินการตรวจสอบ
ผู้เรียนจะตั้งค่า validationLevel (strict เทียบกับ moderate) และ validationAction (error เทียบกับ warn) เพื่อควบคุมวิธีจัดการการละเมิด
ระดับและการดำเนินการตรวจสอบ เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Controlling How Strict Validation Is
MongoDB gives you two independent knobs to tune schema validation behaviour: validationLevel controls which documents are subject to validation, while validationAction controls what happens when a document fails validation. Together they let you introduce validation gradually into existing collections without breaking current data or applications.
validationLevel: strict
strict is the default validation level. In strict mode, every insert and every update must pass the validator—no exceptions. If an existing document in the collection already violates the schema, attempting to update it will still be checked against the validator. Strict mode gives you the strongest data quality guarantee but can be disruptive when applied to a collection with legacy non-conforming documents.
db.runCommand({
collMod: 'users',
validator: { $jsonSchema: { /* ... */ } },
validationLevel: 'strict' // default — all inserts and updates must pass
});validationLevel: moderate
moderate level applies the validator only to new inserts and to updates of documents that already pass the validator. Existing non-conforming documents can still be updated without being forced to comply. This is a safe migration path: you enable the validator on a live collection without breaking updates to old documents that don't yet match the new schema.
db.runCommand({
collMod: 'users',
validator: { $jsonSchema: { /* ... */ } },
validationLevel: 'moderate' // existing non-conforming docs can still be updated
});validationLevel: off
Setting validationLevel to off disables validation entirely, even if a validator is attached to the collection. This is useful during bulk data migrations or emergency hotfixes where you need to write non-conforming data temporarily. Always re-enable validation after the migration window closes.
// Temporarily disable validation for a migration window
db.runCommand({
collMod: 'users',
validationLevel: 'off'
});
// ... run migration ...
// Re-enable strict validation
db.runCommand({
collMod: 'users',
validationLevel: 'strict'
});validationAction: error
error is the default validation action. When a document fails validation, MongoDB rejects the write entirely and returns an error to the client. The document is not written. This is the safest setting for production because it prevents malformed data from ever entering the collection.
db.runCommand({
collMod: 'orders',
validator: { $jsonSchema: { /* ... */ } },
validationAction: 'error' // default: reject the write, return an error
});validationAction: warn
warn action allows the document to be written even if it fails validation, but logs a warning message to the MongoDB server log. This is useful during a transition period when you want to observe how many violations occur without blocking existing application traffic. After examining the logs and fixing the offenders, you can switch to error action.
db.runCommand({
collMod: 'legacy_collection',
validator: { $jsonSchema: { /* ... */ } },
validationAction: 'warn' // write succeeds, violation logged to server log
});
// The server log will show:
// [conn1] Document failed validation: { ... } with schema: { ... }Combining Level and Action
The two settings compose independently. A common migration strategy is to start with validationLevel: 'moderate' and validationAction: 'warn'—new documents must comply but get logged on failure, while old documents are untouched. After observing the warnings and backfilling old data, switch to strict + error for full enforcement.
// Phase 1: observe without blocking
db.runCommand({
collMod: 'users',
validator: { $jsonSchema: { bsonType: 'object', required: ['email'] } },
validationLevel: 'moderate',
validationAction: 'warn'
});
// Phase 2 (after backfill): full enforcement
db.runCommand({
collMod: 'users',
validationLevel: 'strict',
validationAction: 'error'
});Reading the Validation Configuration
Check the current validation settings on a collection using db.getCollectionInfos(). The response includes options.validationLevel and options.validationAction alongside the full validator document. This is useful to audit all collections in a database and verify that production collections have strict enforcement enabled.
const info = db.getCollectionInfos({ name: 'users' });
const opts = info[0].options;
console.log('level:', opts.validationLevel);
console.log('action:', opts.validationAction);
console.log('validator:', JSON.stringify(opts.validator, null, 2));Bypassing Validation With bypassDocumentValidation
Certain database operations support a bypassDocumentValidation: true option that skips the validator for that specific write. Only users with the bypassDocumentValidation privilege can use this option. It is intended for trusted admin scripts and data migrations only—never use it in application code as it defeats the purpose of having a validator.
// Insert a document bypassing validation — admin/migration use only
db.users.insertOne(
{ name: 'LegacyUser' }, // missing required email
{ bypassDocumentValidation: true }
);Validation Warnings in the Server Log
When validationAction is warn, each failed validation is written to the MongoDB server log with the WRITE component and WARNING severity. The log line includes the database, collection, the violating document's _id, and the specific schema rule that was broken. You can monitor these logs with Atlas's log viewer or by tailing mongod.log on self-hosted deployments.
Practical Migration Playbook
Here is the recommended four-phase playbook for adding validation to an existing production collection:
- Phase 1: Set
moderate+warn— no impact, observe violations - Phase 2: Fix application code to send compliant documents
- Phase 3: Backfill old non-conforming documents with a migration script
- Phase 4: Switch to
strict+error— full enforcement
Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: validationLevel (strict/moderate/off) controls which documents are validated, validationAction (error/warn) controls whether failures block or just log, and combining moderate + warn is the safest way to introduce validation on a live collection. Next up we learn how to evolve schemas without downtime on a running MongoDB cluster.
เรียนรู้ JavaScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 30
- บทเรียน
- 120
คำถามที่พบบ่อย
บทเรียน “ระดับและการดำเนินการตรวจสอบ” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ระดับและการดำเนินการตรวจสอบ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ระดับและการดำเนินการตรวจสอบ”
ผู้เรียนจะตั้งค่า validationLevel (strict เทียบกับ moderate) และ validationAction (error เทียบกับ warn) เพื่อควบคุมวิธีจัดการการละเมิด คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “ระดับและการดำเนินการตรวจสอบ” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การเพิ่มตัวตรวจสอบให้คอลเลกชัน
- ข้อจำกัดด้านชนิด ฟิลด์ที่จำเป็น และค่าที่ระบุไว้
- ระดับและการดำเนินการตรวจสอบ
- การพัฒนาสคีมาโดยไม่หยุดให้บริการ