Skip to content

Interview Revision

Revision: Node.js, Mongoose and Production

Pooling, transactions, replica sets, sharding and the Mongoose versus driver choice.

AdvancedAbout 7 minutes
  • One MongoClient per process. Pool inside. Not per request. Cache on globalThis in Next. Never in the browser.
  • ObjectId from params. toArray() only with limit. Duplicate key 11000.
  • Pagination API. { items, next } opaque cursor. Cap limit. No client skip on large collections.
  • Single doc atomic. $inc + filter (stock: { $gte: 1 }). Txn when two docs must commit together. withTransaction retries 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; updateOne does not unless runValidators. populate is 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 readWrite on app db. URI in secrets. No find(req.body).

Interview question

Why not create a new MongoClient per request?

Think about it first.

Interview question

Does MongoDB support transactions, and when do you need them?

Think about it first.

Interview question

What do write concern and read preference control?

Think about it first.