Q60 [Scenario]: Fetching 500,000 documents via Model.find() causes Node.js Out-Of-Memory (OOM) crashes. How do you resolve this?
Model.find() loads all 500,000 documents into application RAM simultaneously as array objects. Resolve this by streaming documents using Mongoose Cursor Stream (Model.find().cursor()) or batching with .eachAsync() or cursor .next(), processing documents sequentially with low memory overhead.
Streaming Documents using Mongoose Cursor
const cursor = User.find({ status: 'active' }).cursor();
for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
await processDocument(doc); // Process one document at a time in memory
}Streams documents sequentially from the database, preventing Node.js RAM exhaustion.
Key Takeaways
Never load massive datasets into application RAM arrays.
Use streams (
.cursor()) to process documents in small memory chunks.
Knowledge Check
Which method returns a Node.js stream for processing large query datasets sequentially without flooding application RAM?