Mongoose Connect: Step-by-Step Guide to Connecting Node.js Server to MongoDB Atlas
Welcome to this course section where we’ll learn how to connect a Node.js server with a MongoDB Atlas database using mongoose.connect
.
Step 1: Install Mongoose
Navigate to your Node.js project directory and run:
npm install mongoose @types/mongoose
Mongoose is a Node.js ODM (Object Data Modeling) library that simplifies communication between your application and MongoDB.
Step 2: Set Up MongoDB Atlas
-
Log in to MongoDB Atlas.
-
Go to Database Access → click Edit to update your password.
Note down your username and new password.
-
Head to the Clusters Dashboard → click Connect.
-
In the popup, choose Drivers → copy the connection string provided.
If you don’t already have a database:
-
Go to Cluster → Collections → Create Database.
-
Set:
-
Database Name:
test
-
Collection Name:
user
-
Step 3: Allow Network Access
-
Go to Network Access.
-
Click Edit on the right-hand side.
-
In the popup, either:
-
Add your current IP address (recommended for security)
-
Or allow access from any IP (less secure)
-
Step 4: Use mongoose.connect
in Your Code
In your index.ts
file, add the following code:
import * as mongoose from ‘mongoose’; const DB_URI = ‘mongodb+srv://<username>:<password>@cluster.xiffugv.mongodb.net/?retryWrites=true&w=majority&appName=Cluster’; mongoose.connect(DB_URI, { dbName: ‘test’, }) .then(() => console.log(‘✅ MongoDB connected successfully’)) .catch(err => { console.error(‘❌ MongoDB connection error:’, err.message); process.exit(1); }); mongoose.connection.on(‘connected’, () => { console.log(‘Mongoose connected to DB’); }); mongoose.connection.on(‘error’, (err) => { console.log(‘Mongoose connection error:’, err); }); mongoose.connection.on(‘disconnected’, () => { console.log(‘Mongoose disconnected’); });
Replace <username>
and <password>
with your actual MongoDB credentials.
Step 5: Start Your Server
From your project root directory:
npm start
Expected Output:
Server is running at port 5000 Mongoose connected to DB ✅ MongoDB connected successfully
Congratulations! You’ve now successfully connected your Node.js server to MongoDB using
mongoose.connect
.