Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 37 ยท Getting Started

Installing Mongoose and Connecting to MongoDB

Install Mongoose with npm, write a connection string, connect with mongoose.connect, handle connection events and shut down cleanly.

Before you can define a single model you need three things: Node.js, a MongoDB server you can reach, and the mongoose package. This lesson walks through all three on your own machine, then explains the connection string, the connection states and how to handle failures. Since this site cannot start a database, the commands appear in read-only blocks and the runnable examples simulate the connection lifecycle.

Prerequisites

  • Node.js 20 or newer (current Mongoose releases require a modern Node; Node 24 LTS is a good choice).
  • A MongoDB server. Either install MongoDB Community Edition locally (it listens on port 27017 by default), run it in a container, or create a free cluster on MongoDB Atlas and copy its connection string.

Check Node first:

Terminal
node --version

Create a project folder, initialise it and install the library:

Terminal
mkdir mongoose-demo
cd mongoose-demo
npm init -y
npm install mongoose

Open package.json and add "type": "module" so you can use import syntax, as every example in this course does. Mongoose also works with CommonJS (const mongoose = require('mongoose')).

The connection string

A MongoDB connection string is a URI. Its parts:

TEXT
mongodb://username:password@host:port/databaseName?option=value
Part Meaning
mongodb:// Scheme for a standard host list. Atlas uses mongodb+srv://, which looks up hosts in DNS.
username:password@ Optional credentials. Special characters in the password must be percent-encoded.
host:port Where the server listens. Default port is 27017.
/databaseName The database your models use. MongoDB creates it on first write.
?options Settings such as retryWrites=true or authSource=admin.

A local, no-authentication string looks like mongodb://127.0.0.1:27017/blog. Prefer 127.0.0.1 over localhost on recent Node versions: localhost can resolve to the IPv6 address ::1 first, and a server that only listens on IPv4 will refuse the connection.

Never hard-code credentials in source files. Put the string in an environment variable:

JavaScript
// .env is loaded with: node --env-file=.env app.js
const uri = process.env.MONGODB_URI;

Connecting

mongoose.connect() returns a promise. Use await and wrap it in try/catch so a failed start is reported clearly:

JavaScript
import mongoose from 'mongoose';

try {
  await mongoose.connect(process.env.MONGODB_URI, {
    serverSelectionTimeoutMS: 5000,
  });
  console.log('Connected to MongoDB');
} catch (error) {
  console.error('Could not connect:', error.message);
  process.exit(1);
}

serverSelectionTimeoutMS controls how long the driver searches for a usable server before giving up. The default is 30 seconds, which feels like a hang when the database is simply not running, so a shorter value gives faster feedback during development.

You normally connect once, when the application starts, and reuse that connection everywhere. Mongoose keeps a connection pool (by default up to 100 sockets) behind mongoose.connection, so there is no need to connect per request.

Connection states and events

mongoose.connection.readyState is a number:

Value State
0 disconnected
1 connected
2 connecting
3 disconnecting

The connection is an event emitter. The useful events are connected, disconnected, error and reconnected:

JavaScript
mongoose.connection.on('connected', () => console.log('connected'));
mongoose.connection.on('disconnected', () => console.log('disconnected'));
mongoose.connection.on('error', (err) => console.error('connection error', err));

If the connection drops after a successful start, the driver reconnects on its own; listen for events if you want to log it.

stateDiagram-v2
  [*] --> disconnected
  disconnected --> connecting: connect()
  connecting --> connected: server found
  connecting --> disconnected: timeout or error
  connected --> disconnecting: close()
  disconnecting --> disconnected

The lifecycle behind readyState.

Stand-in: a fake connection with the same events

This is not Mongoose. It is a small class built on Node's EventEmitter that follows the same state numbers so you can see how code reacts to events and failures.

Node.js Connection lifecycle (stand-in, not Mongoose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Reading a connection string

You can inspect a connection string with the URL class, which understands the mongodb:// shape well enough for a single host. (Real drivers have their own parser for multi-host strings.) Notice how the password is hidden before logging; never print a full URI.

Node.js Taking a connection string apart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second string shows percent-encoding: p%40ss is the password p@ss. An unencoded @ in a password would break the host parsing.

Closing cleanly

When a script finishes, close the connection, otherwise Node keeps the process alive because sockets are still open:

JavaScript
await mongoose.connection.close();

For a long-running server, close on a shutdown signal so in-flight operations finish:

JavaScript
process.on('SIGINT', async () => {
  await mongoose.connection.close();
  process.exit(0);
});

Common connection mistakes

  • Connecting inside every request handler. Connect once at startup.
  • Using localhost and getting ECONNREFUSED ::1. Use 127.0.0.1.
  • Forgetting to await. Queries are buffered until the connection is ready (see How Mongoose works), which hides the mistake until a failure arrives much later.
  • Committing the URI with a password. Use environment variables or a secret manager.
  • No database name. MongoDB falls back to a database called test.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does mongoose.connection.readyState equal when the connection is fully established?

    0 is disconnected, 1 is connected, 2 is connecting and 3 is disconnecting.
  2. 2. Why is 127.0.0.1 often safer than localhost in a local connection string?

    Recent Node versions can try ::1 first. If MongoDB only listens on IPv4, the connection fails.
  3. 3. How often should a typical web application call mongoose.connect()?

    Mongoose keeps a connection pool behind one connection. Connect when the app starts and reuse it.
  4. 4. What should you do with a password containing an @ character in a URI?

    An unencoded @ separates credentials from the host, so special characters must be percent-encoded.

Summary

  • Install with npm install mongoose; you need Node.js and a reachable MongoDB server.
  • A connection string holds scheme, credentials, host, port, database name and options.
  • Connect once with await mongoose.connect(uri) and handle errors; keep secrets in environment variables.
  • readyState is 0, 1, 2 or 3; the connection emits connected, disconnected and error events.
  • Close the connection when a script or server shuts down.

Next: Your first model and document