Sling Academy
Home/Node.js/Cannot connect to MongoDB Atlas with Mongoose: How to Fix

Cannot connect to MongoDB Atlas with Mongoose: How to Fix

Last updated: December 30, 2023

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.

Next Article: Mongoose: How to use ‘id’ instead of ‘_id’

Previous Article: How to execute complex queries in Mongoose

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates