Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js Driver

Connection Troubleshooting

On this page

  • Connection Error
  • Check Your Connection String
  • Configure Your Firewall
  • ECONNREFUSED Error
  • Ensure MongoDB and Your Client Use the Same Protocol
  • ECONNRESET Error
  • Control the Number of File Descriptors
  • Authentication Error
  • Check Your Connection String
  • Verify the User Is in the Authentication Database
  • Error Sending Message
  • Check the User Permissions
  • Configure Your Firewall
  • Check the Number of Connections
  • Too Many Open Connections
  • Check the Number of Connections
  • Timeout Error
  • Set connectTimeoutMS
  • Check the Number of Connections

This page offers potential solutions to issues you might encounter when using the MongoDB Node.js driver to connect to a MongoDB deployment.

Note

This page addresses only connection issues. If you encounter any other issues with MongoDB or the driver, visit the following resources:

  • The Frequently Asked Questions (FAQ) for the Node.js driver

  • The Issues & Help page, which has information about reporting bugs, contributing to the driver, and finding additional resources

  • The MongoDB Community Forums for questions, discussions, or general technical support

The following error message indicates that the driver cannot connect to a server on the specified hostname or port. Multiple situations can generate this error message. In this sample error message, the hostname is 127.0.0.1 and the port is 27017:

Error: couldn't connect to server 127.0.0.1:27017

The following sections describe actions you can take to potentially resolve the issue.

Verify that the hostname and port number in the connection string are both accurate. The default port value for a MongoDB instance is 27017, but you can configure MongoDB to communicate on another port.

Verify that the ports your MongoDB deployment listens on are not blocked by a firewall on the same network. MongoDB uses port 27017 by default. To learn more about the default ports MongoDB uses and how to change them, see Default MongoDB Port.

Warning

Do not open a port in your firewall unless you are sure it's the port used by your MongoDB deployment.

If the connection is refused when the driver attempts to connect to the MongoDB instance, it generates this error message:

MongoServerSelectionError: connect ECONNREFUSED <IPv6 address>:<port>

The following sections describe actions you can take to potentially resolve the issue.

In Node.js v17 and later, the DNS resolver uses IPv6 by default when both the client and host support both. For example, if MongoDB uses IPv4 and your client uses IPv6, the driver returns the previous error message.

You can configure your MongoDB deployment to use IPv6 mode when starting with mongod or mongos. For more information about how to specify IPv6 mode, see IP Binding in the server manual.

As an alternative, you can explicitly use IPv4 with your client by specifying family: 4 as an option to your MongoClient.

const client = new MongoClient(uri, {
family: 4,
});

If the connection is reset when the driver calls client.connect(), it generates this error message:

MongoServerSelectionError: connect ECONNRESET ::<IP address>:<port>

The following section describes a method that may help resolve the issue.

A file descriptor is a unique identifier associated with an open process. In most operating systems, each open connection from the driver is associated with a file descriptor. Operating systems typically have a limit on the number of file descriptors used by a single process. An ECONNRESET error can occur if the number of connections exceeds this limit.

You can set the maximum number of connections by setting maxPoolSize. To resolve this error, you can decrease the number of maximum allowed connections by setting the value of maxPoolSize. Alternatively, you could increase the file descriptor limit in your operating system.

Warning

Changing the configuration of your operating system should always be done with caution.

The Node.js driver can fail to connect to a MongoDB instance if the authorization is not configured correctly. If you are using SCRAM-SHA-256 for authentication and the driver fails to connect, the driver might raise an error message similar to one of the following messages:

Command failed with error 18 (AuthenticationFailed): 'Authentication
failed.' on server <hostname>:<port>.
connection() error occurred during connection handshake: auth error:
sasl conversation error: unable to authenticate using mechanism
"SCRAM-SHA-256": (AuthenticationFailed) Authentication failed.

The following sections describe actions you can take to potentially resolve the issue.

An invalid connection string is the most common cause of authentication issues when attempting to connect to MongoDB using SCRAM-SHA-256.

Tip

For more information about connection strings, see Connection URI in the Connection Guide.

If your connection string contains a username and password, ensure that they are in the correct format. If the username or password includes any of the following characters, they must be percent encoded:

: / ? # [ ] @

The following example shows how to percent encode "#MyP@assword?":

console.log(encodeURIComponent('#MyP@assword?'));

This results in the following output:

"%23MyP%40assword%3F"

To successfully authenticate a connection by using a username and password with SCRAM-SHA-256, the username must be defined in the authentication database. The default authentication database is the admin database. To use a different database for authentication, specify the authSource in the connection string. The following example instructs the driver to use users as the authentication database:

const { MongoClient } = require("mongodb");
const uri = "mongodb://<username>:<password>@<hostname>:<port>/?authSource=users";
const client = new MongoClient(uri);

You can check if this is the issue by attempting to connect to a MongoDB instance hosted on the local machine with the same code. A deployment on the same machine doesn't require any authorization to connect.

When the driver fails to send a command after you make a request, it may display the following error message:

com.mongodb.MongoSocketWriteException: Exception sending message

The following sections describe actions you can take to potentially resolve the issue.

Verify that you've accessed the MongoDB deployment with the correct user. The term "message" in the error can be a command sent by the driver. If you are using a user that doesn't have permissions to send the command, the driver could generate this error.

Also ensure that the user has the appropriate permissions for the message you are sending. MongoDB uses Role-Based Access Control (RBAC) to control access to a MongoDB deployment. For more information about how to configure RBAC in MongoDB, see Default MongoDB Port.

The firewall needs to have an open port for communicating with the MongoDB instance. For more information about configuring the firewall, see Configure Your Firewall in the Connection Error section.

Each MongoClient instance supports a maximum number of concurrent open connections in its connection pool. You can configure the parameter maxPoolSize which defines this limit. The default value is 100. If there are already a number of open connections equal to maxPoolSize, the server waits until a connection becomes available. If this wait time exceeds the maxIdleTimeMS value, the driver responds with an error.

For more information about how connection pooling works, see How Does Connection Pooling Work in the Node Driver? in the FAQ.

The driver creates the following error message when it attempts to open a connection, but it's reached the maximum number of connections:

connection refused because too many open connections

The following section describes a method that may help resolve the issue.

To create more open connections, increase the value of maxPoolSize. For more information about checking the number of connections, see Check the Number of Connections in the Error Sending Message section.

When the network is not able to deliver a request from the driver to the server quickly enough, it can time out. When this happens, you might receive an error message similar to the following message:

timed out while checking out a connection from connection pool: context canceled

If you receive this error, try the following action to resolve the issue.

The driver may hang when it's unable to establish a connection because it takes too long attempting to reach unreachable replica set nodes. You can limit the time the driver spends attempting to establish the connection by using the connectTimeMS setting. To learn more about this setting, see the Timeout Options in the server manual.

You should ensure the connectTimeoutMS setting is not lower than the highest network latency you have to a member of the set. If one of the secondary members has a latency of 10000 milliseconds, setting the connectTimeoutMS to 9000 prevents the driver from ever connecting to that member.

The following example sets connectTimeoutMS to 10000 milliseconds.

const client = new MongoClient(uri, {
connectTimeoutMS: 10000,
});

The number of connections to the server may exceed maxPoolSize. For more information about checking the number of connections, see Check the Number of Connections in the Error Sending Message section.

←  FAQIssues & Help →