Docs HomeNode.js

Connection Troubleshooting连接故障排除

This page offers potential solutions to issues you might encounter when using the MongoDB Node.js driver to connect to a MongoDB deployment.本页提供了使用MongoDB Node.js驱动程序连接到MongoDB部署时可能遇到的问题的潜在解决方案。

Note

This page addresses only connection issues. If you encounter any other issues with MongoDB or the driver, visit the following resources:此页仅解决连接问题。如果您在MongoDB或驱动程序方面遇到任何其他问题,请访问以下资源:

Connection Error连接错误

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:多种情况可能会生成此错误消息。在此示例错误消息中,主机名为127.0.0.1,端口为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.以下各节介绍了可能解决该问题的措施。

Check Your Connection String检查连接字符串

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.MongoDB实例的默认端口值是27017,但您可以将MongoDB配置为在另一个端口上通信。

Configure Your Firewall配置防火墙

Verify that the ports your MongoDB deployment listens on are not blocked by a firewall on the same network. 验证MongoDB部署侦听的端口是否未被同一网络上的防火墙阻止。MongoDB uses port 27017 by default. MongoDB默认使用27017端口。To learn more about the default ports MongoDB uses and how to change them, see Default MongoDB Port.要了解有关MongoDB使用的默认端口以及如何更改它们的更多信息,请参阅默认MongoDB端口

Warning

Do not open a port in your firewall unless you are sure it's the port used by your MongoDB deployment.不要在防火墙中打开端口,除非您确定它是MongoDB部署使用的端口。

ECONNREFUSED Error

If the connection is refused when the driver attempts to connect to the MongoDB instance, it generates this error message:如果驱动程序尝试连接到MongoDB实例时拒绝连接,则会生成以下错误消息:

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

The following sections describe actions you can take to potentially resolve the issue.以下各节介绍了可能解决该问题的措施。

Ensure MongoDB and Your Client Use the Same Protocol确保MongoDB和您的客户端使用相同的协议

In Node.js v17 and later, the DNS resolver uses IPv6 by default when both the client and host support both. 在Node.js v17及更高版本中,当客户端和主机都支持IPv6时,DNS解析程序默认使用IPv6。For example, if MongoDB uses IPv4 and your client uses IPv6, the driver returns the previous error message.例如,如果MongoDB使用IPv4,而您的客户端使用IPv6,则驱动程序会返回以前的错误消息。

You can configure your MongoDB deployment to use IPv6 mode when starting with mongod or mongos. mongodmongos开始时,您可以将MongoDB部署配置为使用IPv6模式。For more information about how to specify IPv6 mode, see IP Binding in the server manual.有关如何指定IPv6模式的更多信息,请参阅服务器手册中的IP绑定

As an alternative, you can explicitly use IPv4 with your client by specifying family: 4 as an option to your MongoClient.作为一种选择,您可以通过将family: 4指定为MongoClient的一个选项,将IPv4明确地用于您的客户端。

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

ECONNRESET Error

If the connection is reset when the driver calls client.connect(), it generates this error message:如果驱动程序调用client.connect()时重置了连接,则会生成以下错误消息:

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

The following section describes a method that may help resolve the issue.以下部分介绍了一种可能有助于解决此问题的方法。

Control the Number of File Descriptors控制文件描述符的数量

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.如果连接数超过此限制,则可能发生ECONNRESET错误。

You can set the maximum number of connections by setting maxPoolSize. 您可以通过设置maxPoolSize来设置最大连接数。To resolve this error, you can decrease the number of maximum allowed connections by setting the value of maxPoolSize. 若要解决此错误,可以通过设置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.更改操作系统的配置时应始终小心谨慎。

Authentication Error身份验证错误

The Node.js driver can fail to connect to a MongoDB instance if the authorization is not configured correctly. 如果授权配置不正确,Node.js驱动程序可能无法连接到MongoDB实例。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:如果使用SCRAM-SHA-256进行身份验证,而驱动程序无法连接,则驱动程序可能会引发类似以下消息之一的错误消息:

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.以下各节介绍了可能解决该问题的措施。

Check Your Connection String检查连接字符串

An invalid connection string is the most common cause of authentication issues when attempting to connect to MongoDB using SCRAM-SHA-256.当尝试使用SCRAM-SHA-256连接到MongoDB时,无效的连接字符串是身份验证问题的最常见原因。

Tip

For more information about connection strings, see Connection URI in the Connection Guide.有关连接字符串的更多信息,请参阅《连接指南》中的连接URI

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?":以下示例显示如何百分比编码"#MyP@assword?"

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

This results in the following output:这将产生以下输出:

"%23MyP%40assword%3F"

Verify the User Is in the Authentication Database验证用户是否在身份验证数据库中

To successfully authenticate a connection by using a username and password with SCRAM-SHA-256, the username must be defined in the authentication database. 要使用SCRAM-SHA-256使用用户名和密码成功验证连接,必须在验证数据库中定义用户名。The default authentication database is the admin database. 默认的身份验证数据库是admin数据库。To use a different database for authentication, specify the authSource in the connection string. 若要使用其他数据库进行身份验证,请在连接字符串中指定authSourceThe following example instructs the driver to use users as the authentication database:以下示例指示驱动程序使用users作为身份验证数据库:

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. 您可以通过尝试使用相同的代码连接到本地机器上托管的MongoDB实例来检查是否存在此问题。A deployment on the same machine doesn't require any authorization to connect.在同一台计算机上进行部署不需要任何授权即可进行连接。

Error Sending Message发送消息时出错

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.以下各节介绍了可能解决该问题的措施。

Check the User Permissions检查用户权限

Verify that you've accessed the MongoDB deployment with the correct user. 验证您是否已使用正确的用户访问了MongoDB部署。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. MongoDB使用基于角色的访问控制(RBAC)来控制对MongoDB部署的访问。For more information about how to configure RBAC in MongoDB, see Default MongoDB Port.有关如何在MongoDB中配置RBAC的更多信息,请参阅默认MongoDB端口

Configure Your Firewall配置防火墙

The firewall needs to have an open port for communicating with the MongoDB instance. 防火墙需要有一个用于与MongoDB实例通信的开放端口。For more information about configuring the firewall, see Configure Your Firewall in the Connection Error section.有关配置防火墙的详细信息,请参阅“连接错误”部分中的“配置防火墙”。

Check the Number of Connections检查连接数量

Each MongoClient instance supports a maximum number of concurrent open connections in its connection pool. 每个MongoClient实例在其连接池中支持最大数量的并发开放连接。You can configure the parameter maxPoolSize which defines this limit. 您可以配置用于定义此限制的参数maxPoolSizeThe default value is 100. 默认值为100If there are already a number of open connections equal to maxPoolSize, the server waits until a connection becomes available. 如果已经有相当于maxPoolSize的打开连接数,则服务器将等待,直到连接可用。If this wait time exceeds the maxIdleTimeMS value, the driver responds with an error.如果此等待时间超过maxIdleTimeMS值,则驱动程序将以错误进行响应。

For more information about how connection pooling works, see How Does Connection Pooling Work in the Node Driver? in the FAQ.有关连接池如何工作的更多信息,请参阅常见问题解答中的节点驱动程序中的连接池是如何工作的?

Too Many Open Connections打开的连接太多

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.以下部分介绍了一种可能有助于解决此问题的方法。

Check the Number of Connections检查连接数量

If you need to create more open connections, increase maxPoolSize. 如果需要创建更多打开的连接,请增加maxPoolSizeFor more information about checking the number of connections, see Check the Number of Connections in the Error Sending Message section.有关检查连接数的更多信息,请参阅错误发送消息部分的检查连接数

Timeout Error超时错误

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.如果收到此错误,请尝试以下操作来解决问题。

Set 设置connectTimeoutMS

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. 您可以使用connectTimeMS设置来限制驱动程序尝试建立连接所花费的时间。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. 您应该确保connectTimeoutMS设置不低于您对集合成员的最高网络延迟。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.如果其中一个辅助成员的延迟为10000毫秒,则将connectTimeoutMS设置为9000将阻止驱动程序连接到该成员。

The following example sets connectTimeoutMS to 10000 milliseconds.以下示例将connectTimeoutMS设置为10000毫秒。

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

Check the Number of Connections检查连接数量

The number of connections to the server may exceed maxPoolSize. 到服务器的连接数可能超过maxPoolSizeFor more information about checking the number of connections, see Check the Number of Connections in the Error Sending Message section.有关检查连接数的更多信息,请参阅错误发送消息部分的检查连接数