MongoDB
Beginner
1 min read
Document Validation with JSON Schema
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"
})