db.createCollection("orders", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["customerId", "total", "status"],
properties: {
customerId: { bsonType: "string", description: "must be a string and required" },
total: { bsonType: "double", minimum: 0, description: "non-negative number" },
status: {
bsonType: "string",
enum: ["pending", "confirmed", "shipped", "completed", "cancelled"]
},
lineItems: {
bsonType: "array",
minItems: 1,
items: {
bsonType: "object",
required: ["productId", "qty"],
properties: {
productId: { bsonType: "string" },
qty: { bsonType: "int", minimum: 1 }
}
}
}
}
}
},
validationAction: "error",
validationLevel: "strict"
})
try {
await db.collection("orders").insertOne({ total: -10, status: "pending" })
} catch (err) {
if (err.code === 121) {
console.log("Validation failed:", err.message)
}
}
db.runCommand({
collMod: "orders",
validator: {
$jsonSchema: {
}
},
validationLevel: "moderate"
})
await db.collection("orders").insertOne(doc, {
bypassDocumentValidation: true
})