Patterns and Validation

Some modeling problems come up in almost every app. Copy a few fields to save a lookup, keep big documents small, store different kinds of products in one collection, and let the database refuse a document with the wrong shape.

Updated

Modeling Patterns

  1. Copying a Few Fields: the Extended Reference Pattern (Journeyman): An order can keep a product's _id together with a copy of its name and the price paid, so a "my orders" page needs one read and the price stays what the customer paid; copy only a few fields, and decide for each one whether it stays as history or follows the original.
  2. Keeping Documents Small: the Subset and Computed Patterns (Journeyman): A product page shows its five newest reviews from a short copy kept in the product (the subset pattern), and its average rating from a count and a total that each new review adds to with $inc (the computed pattern), so the page never reads or recounts every review.
  3. Different Shapes in One Collection: the Polymorphic Pattern (Journeyman): Bikes, helmets and lights can share one products collection, each with the fields every product has, its own fields, and a type field that says which kind it is, so one query can search them all and another can pick out one kind.

Schema Validation

  1. Schema Validation with $jsonSchema (Journeyman): A collection can refuse documents with the wrong shape; a $jsonSchema validator lists the required fields, each field's type, a minimum and the values allowed, createCollection or collMod attaches it, the error names the rule a document broke, and validationLevel and validationAction decide what is checked and what happens.

Exercise: Product Catalog Rules

  1. Exercise: Product Catalog Rules (Journeyman): Write five mongosh statements for Riverbend Bike Shop's catalog, an order with copied names and prices, a review that keeps the five newest and the numbers behind the average, two searches across bikes, helmets and lights, and the rules that keep bad products out, and let the tests check each one.