Stop 07 · Mongoose ODMTopics · 2/8

Connecting with Mongoose

Part of the MERN Stack Roadmap

In short

Your API is useless if it starts accepting requests before the database is ready. Connecting with Mongoose the right way means one shared connection, clear errors and a server that only opens its doors once MongoDB answers.

mongoose.connect opens one shared connection pool to MongoDB when the server starts. The API should start listening only after the connection succeeds.

The jaadu pulls up a metal shop shutter in the morning, revealing shelves fully stocked with neat boxes and a ready counter.

Think of it like this

Opening the shop shutter

A shopkeeper doesn't raise the shutter until the stock has arrived and the cash counter is set up. Customers who walk in early would find empty shelves. Your server should call listen only after mongoose.connect succeeds.

Watch it happen

Server start-up order

Load .env
mongoose.connect
Connected
app.listen

1/4Read MONGODB_URI from the environment. Stop immediately if it's missing.

The big ideas

What you need to know

Connect once

Call mongoose.connect a single time at start-up. Every model shares that connection pool.

Listen after connecting

await the connection, then call app.listen. A failed connection should stop the process loudly.

Connection events

mongoose.connection emits connected, disconnected and error, which are useful for logs and health checks.

Close gracefully

On SIGINT or SIGTERM, close the HTTP server and call mongoose.disconnect() so in-flight work finishes.

See it in code

Walk through the code

js
1// src/server.js  (run: node --env-file=.env src/server.js)2import mongoose from "mongoose";3import app from "./app.js";4 5const { MONGODB_URI, PORT = 5000 } = process.env;6if (!MONGODB_URI) throw new Error("MONGODB_URI is not set");7 8mongoose.connection.on("disconnected", () => console.warn("MongoDB disconnected"));9 10try {11  await mongoose.connect(MONGODB_URI, { serverSelectionTimeoutMS: 10000 });12  console.log("MongoDB connected");13  const server = app.listen(PORT, () => console.log("API on port " + PORT));14 15  process.on("SIGTERM", () => {16    server.close(() => mongoose.disconnect().then(() => process.exit(0)));17  });18} catch (err) {19  console.error("Could not connect to MongoDB:", err.message);20  process.exit(1);21}

1/6Fail fast if the connection string is missing.

Top-level await works in ES modules, so the start-up order reads top to bottom.

Save yourself the pain

Common mistakes

Oops

Calling mongoose.connect inside every route or controller.

Do this instead

Connect once at start-up. Mongoose reuses the same pool for every query.

Oops

Starting app.listen first and connecting in the background.

Do this instead

Await the connection before listening, so early requests don't fail or hang.

Your mission

A clean start-up script

~20 min

Quick check

Where should mongoose.connect be called in an Express API?

Go deeper

  1. 1Create config/db.js that connects using the URL from process.env.
  2. 2Log a clear message and exit if the connection fails on startup.
  3. 3Listen for connection events like disconnected to spot network problems.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge