Sling Academy
Home/Node.js/Fix MongooseServerSelectionError: connect ECONNREFUSED

Fix MongooseServerSelectionError: connect ECONNREFUSED

Last updated: December 30, 2023

Understanding the Error

The MongooseServerSelectionError with the ECONNREFUSED message you encountered is a connection error that occurs when Mongoose, an Object Data Modeling (ODM) library for MongoDB and Node.js, fails to connect to a MongoDB server. This could happen due to several reasons such as MongoDB service not running, incorrect connection strings, network issues, or configuration errors.

Check-Up & Solutions

Verifying MongoDB Service

Before diving into code, ensure that the MongoDB service is up and running on the host and port you are attempting to connect to. If you’re using a local database, verify that mongod is active. For managed cloud instances like MongoDB Atlas, check that the service is operational and accessible from your IP address.

Double-Checking Connection URIs

The connection string plays a crucial role in establishing a connection with the server. Double-check the syntax and components of your MongoDB URI:

const uri = 'mongodb://username:password@host:port/database';

Make sure to replace username, password, host, port, and database with the applicable details. Authentication might not be required for all setups, and configurations such as ssl=true or retryWrites=true add more layers of complexity that should be correct for a successful connection.

Updating Network Access Configuration

Your node may be running in an environment that requires specific network allowances. When using cloud-based databases, you will usually need to configure your IP for access. For local development, it could be related to firewall settings or network permissions. Adjust these configurations accordingly.

Handling Error in Code

Gracefully capturing the error can help debug the cause and provides a fallback for your application. Implement error handling in your code:

const mongoose = require('mongoose');

async function connectToDatabase() {
  try {
    await mongoose.connect('your-mongodb-uri', { useNewUrlParser: true, useUnifiedTopology: true });
    console.log('Successfully connected to MongoDB.');
  } catch (error) {
    console.error('Error connecting to MongoDB:', error);
  }
}

connectToDatabase();

Using async/await syntax allows for a more readable and compact error handling mechanism.

Reviewing Mongoose Options

Review options such as useNewUrlParser and useUnifiedTopology. These are commonly set to true for comprehensiveness in dealing with different connection string formats and using the new server discovery and monitoring engine, respectively. However, inspecting and tailoring your mongoose configuration may resolve the issue.

Code Example

This comprehensive example follows modern JavaScript syntax and good practices. It demonstrates trying to connect to the database and handling the potential errors gracefully:

import mongoose from 'mongoose';

const DATABASE_URI = 'mongodb://localhost:27017/myDatabase';

async function connectToDatabase() {
  try {
    await mongoose.connect(DATABASE_URI, {
      useNewUrlParser: true,
      useFindAndModify: false,
      useUnifiedTopology: true,
      useCreateIndex: true
    });
    console.log('Connected to the database successfully.');
  } catch (error) {
    console.error('Failed to connect to the database:', error);
  }
}

connectToDatabase();

That’s it. Happy coding!

Next Article: Mongoose: How to Access a Pre-Existing Collection

Previous Article: How to use Mongoose without a schema

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