0Pricing
MongoDB Academy · บทเรียน

การเพิ่มตัวตรวจสอบให้คอลเลกชัน

ผู้เรียนจะแนบตัวตรวจสอบ JSON Schema โดยใช้ createCollection และ collMod เพื่อบังคับใช้ฟิลด์ที่จำเป็นและชนิดข้อมูล

การเพิ่มตัวตรวจสอบให้คอลเลกชัน เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Schema Validation Matters

MongoDB is schema-flexible by default—any document can be inserted regardless of its shape. While this is useful in development, production databases need guardrails to prevent malformed data. MongoDB's schema validation feature lets you attach a JSON Schema rule set to a collection so that only well-formed documents can be inserted or updated, catching data quality problems at the database layer before they propagate.

JSON Schema as the Validation Language

MongoDB uses the industry-standard JSON Schema specification (draft 4) to express validation rules. You define a $jsonSchema object that declares which fields are required, what types they must be, and any additional constraints. The same format is used everywhere JSON Schema appears—in OpenAPI specs, form libraries, and now MongoDB validators.

Adding a Validator at Collection Creation

Pass a validator option when calling db.createCollection(). The validator contains a $jsonSchema document. The example below requires every users document to have a name (string) and an email (string), and optionally an age (integer).

db.createCollection('users', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['name', 'email'],
      properties: {
        name:  { bsonType: 'string', description: 'must be a string and is required' },
        email: { bsonType: 'string', description: 'must be a string and is required' },
        age:   { bsonType: 'int',    minimum: 0, description: 'optional, must be a non-negative int' }
      }
    }
  }
});

Adding a Validator to an Existing Collection

Use the collMod (collection modification) command to attach or update a validator on a collection that already exists and may already contain data. This does not validate existing documents by default—it only applies to future writes unless you also change validationLevel.

db.runCommand({
  collMod: 'users',
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['name', 'email'],
      properties: {
        name:  { bsonType: 'string' },
        email: { bsonType: 'string' }
      }
    }
  }
});

What Happens When Validation Fails

By default, if a document violates the validator, MongoDB rejects the write and throws an error: Document failed validation. The error includes a details field explaining exactly which rule was broken, making it easy to diagnose and fix the offending document. The insert or update is rolled back completely—no partial writes occur.

// This insert violates the validator — email is missing
try {
  db.users.insertOne({ name: 'Bob' });
} catch (err) {
  console.error(err.errInfo.details);
  // Output: required field 'email' is missing
}

Viewing the Current Validator

To inspect the validator attached to a collection, use db.getCollectionInfos() or query the system.js namespace. The returned document includes the full validator specification under options.validator, allowing you to review, copy, or compare validators across environments.

// List all collections and their options, including validators
const info = db.getCollectionInfos({ name: 'users' });
console.log(JSON.stringify(info[0].options.validator, null, 2));

Removing a Validator

To remove all validation from a collection, run collMod with an empty validator object. This returns the collection to its default schema-free state. You might do this temporarily during a bulk data migration or permanently when retiring validation in favour of application-layer checks.

// Remove the validator entirely
db.runCommand({
  collMod: 'users',
  validator: {}
});

Validation in Mongoose vs Native MongoDB

Mongoose has its own schema validation at the ODM layer that runs in JavaScript before sending data to MongoDB. However, Mongoose validation can be bypassed with insertMany or direct driver calls. Adding a JSON Schema validator at the database level creates an additional safety net that no client can bypass, regardless of the driver or language used.

Nested Object Validation

JSON Schema validators can reach into embedded sub-documents. Use the properties key to define rules for nested fields, and mark the nested object itself with bsonType: 'object'. This allows you to validate every level of a hierarchical document.

db.createCollection('orders', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['customerId', 'shippingAddress'],
      properties: {
        customerId: { bsonType: 'objectId' },
        shippingAddress: {
          bsonType: 'object',
          required: ['street', 'city'],
          properties: {
            street: { bsonType: 'string' },
            city:   { bsonType: 'string' }
          }
        }
      }
    }
  }
});

Array Item Validation

To validate that an array field contains only documents of a specific shape, use items inside the property definition. Each element of the array will be validated against the items schema. This is useful for enforcing the shape of embedded line items, tags, or address arrays.

db.createCollection('carts', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      properties: {
        items: {
          bsonType: 'array',
          items: {
            bsonType: 'object',
            required: ['productId', 'qty'],
            properties: {
              productId: { bsonType: 'objectId' },
              qty: { bsonType: 'int', minimum: 1 }
            }
          }
        }
      }
    }
  }
});

Schema Validation in Atlas

MongoDB Atlas provides a graphical interface for building and editing collection validators without writing raw JSON. Under the collection's Schema tab you can add properties, set types, and mark required fields through a form. Atlas also shows a validation score—the percentage of existing documents that pass the current schema—helping you measure data quality before enforcing strict validation.

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: JSON Schema validators are attached via createCollection or collMod, validation failures reject the write and return a detailed error, and nested objects and arrays can also be validated within the same schema document. Next up we explore type, required, and enum constraints in depth.

คำถามที่พบบ่อย

บทเรียน “การเพิ่มตัวตรวจสอบให้คอลเลกชัน” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การเพิ่มตัวตรวจสอบให้คอลเลกชัน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การเพิ่มตัวตรวจสอบให้คอลเลกชัน”

ผู้เรียนจะแนบตัวตรวจสอบ JSON Schema โดยใช้ createCollection และ collMod เพื่อบังคับใช้ฟิลด์ที่จำเป็นและชนิดข้อมูล คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “การเพิ่มตัวตรวจสอบให้คอลเลกชัน” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม

ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การเพิ่มตัวตรวจสอบให้คอลเลกชัน
  2. ข้อจำกัดด้านชนิด ฟิลด์ที่จำเป็น และค่าที่ระบุไว้
  3. ระดับและการดำเนินการตรวจสอบ
  4. การพัฒนาสคีมาโดยไม่หยุดให้บริการ
← กลับไปที่ MongoDB Academy