Mongoose and MongoDB patterns — schema design, validation, indexes, virtuals,
99
99%
Does it follow best practices?
Impact
100%
1.11xAverage score across 5 eval scenarios
Passed
No known issues
A fintech company is building a digital wallet service where users can transfer funds between accounts. The engineering team has flagged a critical bug in a prototype: during load testing, some transfers partially completed — one account was debited but the other was not credited — leaving users with missing funds and no clear error. This happened because the two database updates were executed independently, and a network error interrupted the second one.
The team needs a production-ready fund transfer function that ensures both the debit and credit operations either succeed together or neither happens. The system runs on MongoDB with a replica set configuration.
Write a TypeScript file at wallet-service.ts that implements:
Wallet Mongoose model with at minimum: userId (string), balanceCents (number, minimum 0), and appropriate schema options.transfer(fromUserId, toUserId, amountCents) async function that moves funds atomically from one wallet to another.The transfer function should handle the case where amountCents is 0 or negative by throwing an error. It should also handle insufficient funds gracefully. Make sure the implementation correctly releases all database resources even if the transfer fails partway through.
No input files required.