Common Mistakes
skip() and Over-fetching
Deep offsets and SELECT * for documents. What it costs, and what to do instead.
IntermediateAbout 5 minutes
Problem. Page 500 of orders, or a list endpoint that ships every field including nested blobs the UI never shows.
db.orders.find({}).skip(4990).limit(10)
db.users.find({ city: "Bangalore" }) // then delete keys in Nodedb.orders.find({
userId,
$or: [
{ createdAt: { $lt: lastDate } },
{ createdAt: lastDate, _id: { $lt: lastId } }
]
}).sort({ createdAt: -1, _id: -1 }).limit(10)
db.users.find({ city: "Bangalore" }, { name: 1, city: 1, _id: 0 })skip(n) is O(n). Offset is fine for a 20-row admin table. toArray() on unbounded find is the Node version of the same class of bug. countDocuments on every page for '4 of 80,221' is a second heavy query — often drop the total.
Interview question
Why is skip() plus fetching whole documents a production bug?
Think about it first.
skip(n) still traverses n keys every request, so cost grows with page number. Returning full documents when the API needs three fields wastes IO and RAM. I paginate with a cursor and project in the query.
Practice