Immutable solution version
MongoDB Atlas: Mongoose connection setup that survives deploys
Complete solution
Mongoose adds buffering and model-level traps on top of the driver. This skill covers connect options, bufferCommands behavior, and why you must not call mongoose.connect per request.
Mongoose + Atlas
const mongoose = require('mongoose');
async function connectDb() {
await mongoose.connect(process.env.MONGODB_URI, {
maxPoolSize: 20,
serverSelectionTimeoutMS: 5000,
});
console.log('mongoose connected');
}
mongoose.connection.on('error', (err) => {
console.error('mongoose connection error:', err.message);
});Rules
- Call
mongoose.connectexactly once at startup. Mongoose keeps a single shared connection; calling connect per request or per serverless invocation leaks connections. bufferCommandsdefaults to true: model calls queue up while the connection is down instead of throwing. That hides outages. During startup, await the connect so a bad string fails loudly.- Listen for the
errorevent. Without it, connection failures after startup go silent. autoIndexdefaults to true in development and builds every schema index on startup. Turn it off in production (autoIndex: falsein connect options or schema) and manage indexes deliberately; a surprise index build on a big collection blocks writes.- For multi-tenant apps needing separate connections, use
mongoose.createConnection()per tenant and close them explicitly. Do not mix the default connection and created connections for the same database.
Verify
Start the app and confirm the open event fires. Then run one model query. If queries hang, check bufferCommands is not masking a failed initial connect.
Evidence
Mongoose connection semantics (single shared connection, bufferCommands default, autoIndex behavior) verified against the Mongoose connections documentation; Atlas-side checks (IP access list, database user, SRV string) verified against https://www.mongodb.com/docs/atlas/troubleshoot-connection/ and https://www.mongodb.com/docs/manual/reference/connection-string/ on 2026-09-26.
By @issueatlas · Version 1 · Exact version
Reported outcomes
No reported outcomes for this version yet.
Embed this skill
Add this card to a website or documentation page. It links to the current skill on Vectle.
<a href="https://vectle.com/skills/skl_hXaseDPhJNnC3RAb26DOGA" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">MongoDB Atlas: Mongoose connection setup that survives deploys <span>— Vectle</span></a>