Back to blog

Published on Tuesday, January 28, 2025

How to Connect a Node.js App with MongoDB Atlas

How to Connect a Node.js App with MongoDB Atlas

Step 1: Set Up MongoDB Atlas

  1. Go to MongoDB Atlas and sign up for an account.
  2. Create a cluster by selecting your preferred cloud provider and region.
  3. Whitelist your IP address (use 0.0.0.0/0 during development for access from anywhere).
  4. Create a database user with a username, password, and readWrite role.

Step 2: Install Required Packages

In your Node.js project, install the MongoDB driver:

npm install mongoose
npm install -D typescript @types/mongoose

Step 3: Set Up Environment Variables

Create a .env file in your project’s root directory to store your MongoDB Atlas URI:

MONGO_URI=mongodb+srv://<username>:<password>@<cluster-name>.mongodb.net/<database-name>?retryWrites=true&w=majority

Replace the placeholders with actual details.

Note:

Ensure your .env file is included in .gitignore to avoid exposing sensitive information.

Step 4 (Optional): TypeScript Configuration

Create a tsconfig.json file at the root of your project with the following content:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

Step 4 Create a Database Connection File

Create a file named database.js or database.ts:

import mongoose from "mongoose";
		
const connectToDB = async () => {
  try {
    const uri = process.env.MONGO_URI;
		
		// Check if URI exists
    if (!uri) {
      throw new Error("MongoDB URI not found in environment variables.");
    }
    
    await mongoose.connect(uri);
    console.log("Connected to MongoDB Atlas");
  } catch (error) {
    console.error("Error connecting to MongoDB:", error.message);
    process.exit(1);
  }
}

// Call the function to establish the connection
connectToDB();

Step 5: Test the Connection

Start your application using node or nodemon:

npx tsc
node --env-file=.env index.js 

Expected Output:

If everything is configured correctly, you should see:

Connected to MongoDB Atlas

Note:

if you get any errors, feel free to ask any questions in the comments. I will try to solve the issue.

Conclusion

Connecting a Node.js application to MongoDB Atlas is simple and efficient. By following these steps, you can securely store and manage your data in the cloud. If you encounter any issues, feel free to ask in the comments—I’m happy to help! 🚀