15. #MDBlocal
Our New Orders Schema
● Orders must contain a lineitems array of 1 to 10 documents
● Documents embedded in lineitems have fields for:
○ sku (required)
○ name (optional)
○ unit_price (required)
○ quantity (required)
● Value of quantity must be an integer
● (Must also contain fields: total, VAT, totalWithVAT, but we'll get to that.)
17. #MDBlocal
Now Let's Deal with Totals and VAT
The most recent order we looked at actually contains a few errors:
● The totalWithVAT value should be 141 * 1.20 = 169.2
● The total value should be the sum of each line item sub-total
● I.e., (10 * 9) + (10 * 5) = 140
Can we enforce that totalWithVAT and total are correct using validation?
18. #MDBlocal
Yes we can!
● MongoDB 3.6 -- more expressive query syntax
● Can express complex business rules in validations
● E.g, compute and compare multiple values at runtime
19. #MDBlocal
$expr
Check that totalWithVAT == total * (1+VAT):
$expr: {
$eq: [
"$totalWithVAT",
{$multiply: [
"$total",
{$sum: [1, "$VAT"]}
]}
]
}
Let's add this as a validation rule alongside our JSON Schema validation ()