SyntaxStudy
Sign Up
MongoDB Document Validation with JSON Schema
MongoDB Beginner 1 min read

Document Validation with JSON Schema

MongoDB supports collection-level document validation using JSON Schema syntax. You define a validator when creating or modifying a collection, and MongoDB will reject any insert or update that does not satisfy the schema. Validation rules can enforce required fields, data types, minimum and maximum values, string patterns, and the presence or absence of additional properties. The validationAction option controls whether MongoDB rejects invalid documents outright (error) or merely logs a warning (warn). Validation is a powerful way to maintain data integrity without giving up the flexibility of a document model — you can make some fields required while leaving others optional.
Example
// Create a collection with JSON Schema validation
db.createCollection("orders", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["customerId", "items", "total", "status"],
      properties: {
        customerId: {
          bsonType: "objectId",
          description: "must be an ObjectId and is required"
        },
        items: {
          bsonType: "array",
          minItems: 1,
          items: {
            bsonType: "object",
            required: ["productId", "qty", "price"],
            properties: {
              qty:   { bsonType: "int", minimum: 1 },
              price: { bsonType: "double", minimum: 0 }
            }
          }
        },
        total:  { bsonType: "double", minimum: 0 },
        status: { enum: ["pending", "shipped", "delivered", "cancelled"] }
      }
    }
  },
  validationAction: "error"
})