Cannot connect to MongoDB Atlas with Mongoose: How to Fix

Updated: December 30, 2023 By: Guest Contributor Post a comment

When working with Node.js and attempting to connect to MongoDB Atlas using Mongoose, one may sometimes face a connectivity issue. The error message ‘Cannot connect to MongoDB Atlas with Mongoose’ indicates that the application is unable to establish a connection to the MongoDB database. The issues leading to this problem can widely vary from network problems, incorrect connection strings, database configuration issues, to outdated Mongoose versions.

Update Mongoose

Start by ensuring that the version of Mongoose supported by MongoDB Atlas is the one installed in your project. To update Mongoose to the latest version, you can run:

npm install mongoose@latest --save

Configure Correct Connection String

The connectivity issue often boils down to an incorrect connection string. Double-check your MongoDB Atlas connection string which is provided in the Atlas console. It should follow this pattern: mongodb+srv://user:password@host/database?retryWrites=true&w=majority. Make sure to replace user, password, parameters, and database with your actual user credentials, database name and other parameters as needed.

When coding, use environment variables to store sensitive information such as the username, password, and database name to avoid committing them into version control. Here’s an example of how to use environment variables with ‘dotenv’ package:

require('dotenv').config();
const mongoose = require('mongoose');

const dbURI = process.env.MONGODB_URI;
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Database connected!'))
  .catch(err => console.error('Connection error:', err));

Network Access

Verify that your IP address is whitelisted in MongoDB Atlas. In the ‘Network Access’ panel of the Atlas dashboard, add your IP address to the list of the allowed IPs that can access your database. If your application is on a hosting platform or a dynamic IP address, you might consider allowing access from all IP addresses, although for security reasons, it’s better to avoid that for production applications.

Check Your Internet Connection

A simple but sometimes overlooked factor is your internet connection (when you’re working with your local projects on your personal computer). Verify that you have proper internet access and that your connection is stable. MongoDB Atlas is a cloud-hosted service and thus requires a consistent internet connection for interaction.

Database User Permissions

Make sure that the database user has the necessary permissions to access the required databases; this can be configured within the ‘Database Access’ section of the MongoDB Atlas console.

Sample Connection Code

Here is what your connection code might look like with attention to these considerations. This sample uses ES modules, which will require updating your package.json to include “type”: “module” if using Node.js version 13 or above:

import 'dotenv/config';
import mongoose from 'mongoose';

(async () => {
  try {
    const dbURI = process.env.MONGODB_URI;
    await mongoose.connect(dbURI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log('Database connected!');
  } catch (err) {
    console.error('Connection error:', err);
  }
})();

By addressing each of these points, you start eliminating the factors that could cause the ‘Cannot connect to MongoDB Atlas with Mongoose’ error, narrowing down to the actual issue for a successful connection.

Disclaimer: It’s important to note that the cause of the connectivity issue may be very specific to an environment; therefore, all situations have not been covered. This guide addresses the most common issues.