Connecting Node.js Server to MongoDB

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:

sh
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

  1. Log in to MongoDB Atlas.
    Mongodb Atlas Login

  2. Go to Database Access → click Edit to update your password.
    Note down your username and new password.

Mongo DB Database Access

 

Database Access Mongodb AtlasMongo DB Database access Username and generate password

Mongo DB Database Access Update User

  1. Head to the Clusters Dashboard → click Connect.

Mongodb Cluster Connect

  1. In the popup, choose Drivers → copy the connection string provided.

Mongodb Cluster Connect Drivers

 

Mongodb Cluster Connect Strings

If you don’t already have a database:

  • Go to ClusterCollectionsCreate Database.

  • Set:

    • Database Name: test

    • Collection Name: user


Step 3: Allow Network Access

  1. Go to Network Access.

  2. Click Edit on the right-hand side.

Mongodb Atlas Network Access Whitelist

  1. In the popup, either:

    • Add your current IP address (recommended for security)

    • Or allow access from any IP (less secure)

Mongodb Atlas Network Access IP Access Entry List


Step 4: Use mongoose.connect in Your Code

In your index.ts file, add the following code:

sh
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:

sh
npm start

Expected Output:
sh
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.

Scroll to Top