Enforcing BSON Types with Schema Validation

MongoDB schema validation can enforce required fields, BSON types, numeric ranges, string constraints, array element types, and nested document structure.

This is important because an application's intended schema may not otherwise be enforced consistently across all writers.

Example: Define a validated product collection

db.createCollection("validatedProducts", {
 validator: {
 $jsonSchema: {
 bsonType: "object",
 required: ["name", "price", "createdAt"],
 properties: {
 name: {
 bsonType: "string",
 minLength: 1
 },
 price: {
 bsonType: "decimal",
 minimum: NumberDecimal("0")
 },
 createdAt: {
 bsonType: "date"
 },
 tags: {
 bsonType: "array",
 items: {
 bsonType: "string"
 }
 }
 }
 }
 },
 validationAction: "error"
});

The example requires a nonempty name, a nonnegative Decimal128 price, and a BSON Date. If tags is present, it must be an array of strings.

Validation and application schemas

An application library such as Mongoose can also define a schema. That schema controls how the application represents and validates data through that library.

MongoDB collection validation operates at the database layer and can protect the collection from invalid writes made by different applications, subject to validation settings and the privileges available to the writer.

These two mechanisms complement one another rather than being interchangeable.

Validation limitations

Schema validation should not be expected to implement every business rule. Complex workflows may require application logic, transactions, unique indexes, or other database constraints.

For example, a validator can require a nonnegative price, but checking whether an order has enough inventory may require reading and updating related records according to a concurrency-safe workflow.

Validation and migrations

Introducing stricter validation into a collection containing legacy documents requires care. Test the rules against existing data and plan a migration before enforcing requirements that old documents do not satisfy.

Validate BSON types in a collection
db.createCollection("typedProducts", {
 validator: {
 $jsonSchema: {
 bsonType: "object",
 required: ["name", "price"],
 properties: {
 name: { bsonType: "string" },
 price: {
 bsonType: "decimal",
 minimum: NumberDecimal("0")
 },
 createdAt: { bsonType: "date" }
 }
 }
 },
 validationAction: "error"
});

// Valid document.
db.typedProducts.insertOne({
 name: "Keyboard",
 price: NumberDecimal("1999.00"),
 createdAt: new Date()
});

// Invalid: price is a string.
db.typedProducts.insertOne({
 name: "Mouse",
 price: "499.00"
});
💡 The first insert satisfies the required fields and BSON type constraints. The second insert should fail because the price is stored as a string rather than Decimal128. This demonstrates how database validation protects against type inconsistencies.
Key Takeaways
  • Schema validation can enforce BSON types and field constraints.
  • MongoDB validation and Mongoose validation operate at different layers.
  • Validation complements, but does not replace, indexes and application business rules.
  • Strict validation must be planned carefully when existing data contains legacy structures.
  • Consistent BSON types make queries and aggregation more predictable.
Knowledge Check

A collection validator requires `price` to have BSON type `decimal`. Which value satisfies that type requirement?