型、必須、列挙値の制約
JSON Schema バリデーター内で、型の制限、必須フィールド、許可する列挙値を定義します。
「型、必須、列挙値の制約」はCoddyKit上の無料MongoDB Academyレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはMongoDB Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 MongoDB Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
The Three Core Constraint Types
MongoDB JSON Schema validators support three fundamental constraint categories that cover the majority of real-world validation needs: type constraints that enforce the BSON data type of a field, required constraints that mandate the presence of certain fields, and enum constraints that restrict a field's value to a predefined whitelist. Together they form the backbone of any production schema validator.
BSON Types vs JSON Schema Types
JSON Schema uses standard JSON types like string, number, and object. MongoDB extends this with BSON types declared via the bsonType keyword—values like objectId, date, int, long, double, and decimal. Always use bsonType in MongoDB validators (not type) when you need precision about numeric subtypes or MongoDB-specific types like objectId and date.
// BSON type names to use in validators
// 'string', 'bool', 'int', 'long', 'double', 'decimal',
// 'objectId', 'date', 'array', 'object', 'null', 'binData'
db.createCollection('products', {
validator: {
$jsonSchema: {
bsonType: 'object',
properties: {
_id: { bsonType: 'objectId' },
price: { bsonType: 'decimal' },
stock: { bsonType: 'int' },
isActive: { bsonType: 'bool' },
createdAt: { bsonType: 'date' }
}
}
}
});Declaring Required Fields
The required keyword takes an array of field names that must be present in every document inserted or updated in the collection. If any required field is missing, the write is rejected. Required fields are declared at the schema level, not inside individual property definitions.
db.createCollection('employees', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['firstName', 'lastName', 'email', 'hiredAt'],
properties: {
firstName: { bsonType: 'string' },
lastName: { bsonType: 'string' },
email: { bsonType: 'string' },
hiredAt: { bsonType: 'date' },
salary: { bsonType: 'decimal' } // optional
}
}
}
});Enum Constraints: Restricting Allowed Values
The enum keyword restricts a field to a fixed list of permitted values. This is ideal for status fields, category codes, or any field that must come from a controlled vocabulary. Attempting to insert a value outside the enum list causes the write to fail with a validation error.
db.createCollection('tickets', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['title', 'status', 'priority'],
properties: {
title: { bsonType: 'string' },
status: { enum: ['open', 'in_progress', 'resolved', 'closed'] },
priority: { enum: ['low', 'medium', 'high', 'critical'] }
}
}
}
});Numeric Range Constraints
For numeric fields, JSON Schema provides minimum, maximum, exclusiveMinimum, and exclusiveMaximum keywords. These work alongside bsonType to enforce valid ranges—for example, ensuring a product price is positive and a rating falls between 1 and 5.
db.createCollection('reviews', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['productId', 'rating'],
properties: {
productId: { bsonType: 'objectId' },
rating: {
bsonType: 'int',
minimum: 1,
maximum: 5,
description: 'Rating must be between 1 and 5'
},
price: {
bsonType: 'decimal',
minimum: 0,
exclusiveMinimum: true
}
}
}
}
});String Length Constraints
String fields support minLength and maxLength to enforce character count limits. A username might need to be at least 3 characters and at most 30. A description field might have a 2000-character cap. These constraints prevent accidentally storing empty strings or truncated text that exceeds UI display limits.
db.createCollection('profiles', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['username'],
properties: {
username: {
bsonType: 'string',
minLength: 3,
maxLength: 30,
description: 'Username must be 3-30 characters'
},
bio: {
bsonType: 'string',
maxLength: 500
}
}
}
}
});Pattern Constraints for Strings
The pattern keyword accepts a regular expression string and validates that the field value matches it. This is useful for enforcing email format, phone number patterns, UUID format, or slug conventions. Unlike regex queries used for search, pattern constraints run at write time to block non-conforming data from entering the collection.
db.runCommand({
collMod: 'users',
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['email'],
properties: {
email: {
bsonType: 'string',
pattern: '^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$',
description: 'Must be a valid email address'
},
slug: {
bsonType: 'string',
pattern: '^[a-z0-9]+(?:-[a-z0-9]+)*$'
}
}
}
}
});Combining Type and Enum
Type and enum can be combined. Providing both bsonType and enum ensures the value is both of the correct type and within the allowed set. Without bsonType, an enum will accept any type that matches—including a number equal to the string value if JavaScript coercion were involved. Explicit types make validation intent clear.
properties: {
role: {
bsonType: 'string',
enum: ['admin', 'editor', 'viewer'],
description: 'Must be a string and one of the allowed roles'
}
}additionalProperties to Disallow Unknown Fields
By default, MongoDB validators allow any extra fields not mentioned in properties. Setting additionalProperties: false prevents documents from containing fields not declared in the schema. This is a strict mode that can catch typos in field names during development, though it can be too rigid for schemas that evolve frequently.
db.createCollection('strictUsers', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['name', 'email'],
additionalProperties: false, // reject any undeclared fields
properties: {
_id: { bsonType: 'objectId' },
name: { bsonType: 'string' },
email: { bsonType: 'string' }
}
}
}
});Providing Helpful Error Descriptions
The description keyword inside each property definition is included in the validation error message returned to the client. Writing clear, human-readable descriptions like 'Email must be a valid address' or 'Rating must be between 1 and 5' makes it much easier for developers and API consumers to understand and fix validation failures without reading the schema.
Testing Your Validator
After adding a validator, always test it with both valid and invalid documents to confirm it behaves as expected. Try inserting a document missing a required field, a field with the wrong type, and a field with a value outside the enum. Also insert a perfectly valid document to confirm it is accepted. This two-sided testing prevents overly strict validators that block legitimate writes.
// Should FAIL — missing required 'email'
try { db.users.insertOne({ name: 'Bob' }); } catch(e) { console.log('Correctly rejected:', e.code); }
// Should FAIL — wrong type for 'age'
try { db.users.insertOne({ name: 'Bob', email: 'b@b.com', age: 'thirty' }); } catch(e) { console.log('Correctly rejected'); }
// Should PASS
db.users.insertOne({ name: 'Bob', email: 'b@b.com', age: 30 });
console.log('Valid document accepted');Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: bsonType enforces BSON-specific data types including objectId and date, required declares mandatory fields at the schema level, and enum restricts a field to a fixed list of allowed values. Next up we explore validation levels and actions to control how strictly MongoDB enforces these rules.
AI チューターと学ぶ JavaScript — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 30
- レッスン
- 120
よくある質問
「型、必須、列挙値の制約」レッスンは無料ですか?
はい。「型、必須、列挙値の制約」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、MongoDB Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 MongoDB Academyコースには全4レッスンが含まれています。
「型、必須、列挙値の制約」で何を学びますか?
JSON Schema バリデーター内で、型の制限、必須フィールド、許可する列挙値を定義します。 ブラウザで直接実行するハンズオンコードでMongoDB Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
MongoDB Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのMongoDB Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「型、必須、列挙値の制約」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このMongoDB Academyレッスンでコードを書いて実行できますか?
はい。すべてのMongoDB Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。