MongoDB

Atomic updates and transactions

A single-document MongoDB write is atomic. To protect an inventory count, combine the required state in the filter with the update instead of reading a value and later writing an unchecked replacement. For a positive integer request, match the record ID, tenant and sufficient quantity; decrement via $inc. If no document matched, report a domain failure rather than forcing stock negative. An update of multiple documents does not make the entire batch atomic; use supported transactions when cross-document invariants require them, with a session and topology verified for that driver. The local function models the invariant sequentially; actual concurrent safety and server transaction behavior remain untested. If retries may duplicate a reservation, use an idempotency design. Do not perform an unchecked read-modify-write sequence or treat matchedCount as a complete authorization decision. Validate the caller and requested quantity first. Evidence: Dependency-free application model; no external service execution. Source: https://www.mongodb.com/docs/manual/core/write-operations-atomicity/

Formal Syntax & Structure

nodejs syntaxnodejs
See example for the scoped contract

Working Example

Example Snippetnodejs
let qty=4;function reserve(n){if(!Number.isSafeInteger(n)||n<1||n>qty)return false;qty-=n;return true;}console.log(reserve(3),qty);console.log(reserve(3),qty);console.log(reserve(-1),qty);
Node.js Reference