Indexes and validation
Local baseline: Node.js 22.16.0. Dependency-free application model; no external service execution. No third-party packages or external connections.
Try the local example
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));Run node main.mjs in a disposable directory with the files shown. Expected standard output:
storedduplicatestoredinvalidHow it works
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.
Integration example — staged
Static candidate only. Exact package and server versions, dependency/advisory review, integration and compilation NOT RUN. Use only a reviewed disposable fixture; no real connection settings.
// Partial administrative fixture: use only an empty disposable database.export async function setup(db){ const books=await db.createCollection('books',{validator:{$jsonSchema:{bsonType:'object',required:['tenant','sku'],properties:{tenant:{bsonType:'string'},sku:{bsonType:'string'}}}}}); await books.createIndex({tenant:1,sku:1},{unique:true}); return books.find({tenant:'a',sku:'x'}).explain('executionStats');}Creates a disposable collection and compound unique index; returns a plan whose shape is version/data dependent. NOT RUN.
Common mistake
Do not confuse an index with schema validation or tenant authorization. Creating an index does not automatically prevent cross-tenant access.
Practice
Add a second tenant with the same SKU. Verify that only duplicates within the same tenant are rejected in the model.
Documentation: primary source. Candidate lookup: node-indexes-and-validation-lookup. Prerequisite: node-mongodb-documents-and-queries (platform route unverified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Indexes and validation — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
What does the unique compound index enforce?
How should an index benefit be evaluated?
What is the role of schema validation?