MongoDB

Document validation and indexes

A schema validator enforces selected document rules at the database boundary. An index is a separate data structure designed to improve certain lookups and optionally enforce uniqueness. Validate input before writing, and use server-side validation for invariants that must hold across writers. A compound index on tenant and SKU can support tenant-scoped lookups; a unique compound index can prevent duplicate combinations. Indexes add storage and write costs. Use explain execution statistics to inspect the actual MongoDB plan and examined-document counts on representative data. A small collection may still use a scan. The local example models only input shape and duplicate detection, not MongoDB indexing or validation semantics. Do not confuse an index with schema validation or tenant authorization. Creating an index does not automatically prevent cross-tenant access. Evidence: Dependency-free application model; no external service execution. Source: https://www.mongodb.com/docs/manual/core/schema-validation/

Formal Syntax & Structure

nodejs syntaxnodejs
See example for the scoped contract

Working Example

Example Snippetnodejs
const records=new Map();function insert(doc){if(typeof doc.tenant!=='string'||typeof doc.sku!=='string'||!Number.isSafeInteger(doc.qty)||doc.qty<0)return 'invalid';const key=JSON.stringify([doc.tenant,doc.sku]);if(records.has(key))return 'duplicate';records.set(key,{...doc});return 'stored';}for(const doc of [{tenant:'a',sku:'x',qty:1},{tenant:'a',sku:'x',qty:2},{tenant:'b',sku:'x',qty:2},{tenant:'b',sku:'y',qty:-1}])console.log(insert(doc));
Node.js Reference