# Mongoose + Atlas

```js
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.connect` exactly once at startup. Mongoose keeps a single shared connection; calling connect per request or per serverless invocation leaks connections.
- `bufferCommands` defaults 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 `error` event. Without it, connection failures after startup go silent.
- `autoIndex` defaults to true in development and builds every schema index on startup. Turn it off in production (`autoIndex: false` in 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.