Interview Revision
Revision: Node.js, Mongoose and Production
Pooling, transactions, replica sets, sharding and the Mongoose versus driver choice.
- One MongoClient per process. Pool inside. Not per request. Cache on
globalThisin Next. Never in the browser. - ObjectId from params.
toArray()only withlimit. Duplicate key 11000. - Pagination API.
{ items, next }opaque cursor. Caplimit. No clientskipon large collections. - Single doc atomic.
$inc+ filter (stock: { $gte: 1 }). Txn when two docs must commit together.withTransactionretries transients, not sold-out. Do not wrap every$set. - Races. Expected state in the filter. Version field for whole-document edits. Last-
$set-wins is not a merge.
- Mongoose. ODM on the driver.
save()validates;updateOnedoes not unlessrunValidators.populateis a join.lean()for lists.pre('save')≠ query updates. Unique on schema = index. - Replica set. Primary writes, oplog, election. Three voting members typical.
- w: majority survives failover; w: 1 can vanish. Read preference primary for read-after-write; secondaries are stale.
- Shard last, after indexes. Key: cardinality, no monotonic hotspot, present in your filters.
- Atlas operates the cluster. You own schema, indexes, concerns, restores, lag, connections.
- Security. App user
readWriteon app db. URI in secrets. Nofind(req.body).
Interview question
Why not create a new MongoClient per request?
The client owns the pool. Connecting is the expensive handshake. Per-request clients exhaust connections and add latency. One client at startup, close on SIGTERM; serverless caches it.
Interview question
Does MongoDB support transactions, and when do you need them?
Yes, on replica sets. I need them far less than SQL because one document update is already atomic and related data is often embedded. Use them when two documents must not be seen half-applied. Wrapping every write is a schema smell.
Interview question
What do write concern and read preference control?
Write concern is how many members ack the write — majority survives the primary dying before replicate. Read preference is which members may serve reads. Secondaries are wrong for read-after-write because replication is async.