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或驱动程序中遇到任何其他问题,请访问以下资源:
The Issues & Help page, which has information about how to report bugs, contribute to the driver, and find more resources问题和帮助页面,其中包含有关如何报告错误、为驱动程序做出贡献以及查找更多资源的信息The MongoDB Stack Overflow tag or the MongoDB Reddit community for questions, discussions, or general technical supportMongoDB Stack Overflow标签或MongoDB Reddit社区,用于提问、讨论或一般技术支持
Connection Error连接错误
If the driver cannot connect to the specified host, you might get an 如果驱动程序无法连接到指定的主机,您可能会收到MongoServerSelectionError.MongoServerSelectionError。
The following sections describe actions you can take to potentially resolve the issue.以下部分描述了您可以采取的潜在解决问题的操作。
Configure Your Firewall配置防火墙
Verify that the ports your MongoDB deployment listens on are not blocked by a firewall on the same network. MongoDB uses port 验证MongoDB部署监听的端口是否未被同一网络上的防火墙阻止。默认情况下,MongoDB使用端口27017 by default. To learn more about the default ports MongoDB uses and how to change them, see Default MongoDB Port in the MongoDB Server manual.27017。要了解更多关于MongoDB使用的默认端口以及如何更改它们的信息,请参阅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部署使用的端口,否则不要在防火墙中打开该端口。
Check Your Network Access List检查您的网络访问列表
Verify that your IP Address is listed in the IP Access List for your cluster. You can find your IP Access List in the Network Access section of the Atlas UI. 验证您的IP地址是否列在群集的IP访问列表中。您可以在Atlas UI的网络访问部分找到您的IP访问列表。To learn more about how to configure your IP Access List, see the Configure IP Access List Entries guide in the Atlas documentation.要了解有关如何配置IP访问列表的更多信息,请参阅Atlas文档中的“配置IP访问清单条目”指南。
ECONNREFUSED Error错误
If the connection is refused when the driver attempts to connect to the MongoDB instance, it generates an error message similar to the following:如果驱动程序尝试连接到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 IP Address确保MongoDB和您的客户端使用相同的IP地址
In Node.js v17 and later, the DNS resolver uses 在Node.js v17及更高版本中,当客户端和主机都支持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.IPv6时,DNS解析器默认使用IPv6。例如,如果MongoDB使用IPv4,而您的客户端使用IPv6,驱动程序将返回之前的错误消息。
You can configure your MongoDB deployment to use 您可以将MongoDB部署配置为在从IPv6 mode when starting with mongod or mongos. For more information about how to specify IPv6 mode, see IP Binding in the server manual.mongod或mongos开始时使用IPv6模式。有关如何指定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 an error message similar to the following: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. To resolve this error, you can decrease the number of maximum allowed connections by setting the value of maxPoolSize. maxPoolSize来设置最大连接数。要解决此错误,您可以通过设置maxPoolSize的值来减少允许的最大连接数。Alternatively, you could increase the file descriptor limit in your operating system. To learn more about how to set 或者,您可以增加操作系统中的文件描述符限制。要了解有关如何设置maxPoolSize, see the API documentation for maxPoolSize .maxPoolSize的更多信息,请参阅maxPoolSize的API文档。
Warning
Always be cautious when changing the configuration of your operating system.更改操作系统配置时始终要小心。
Authentication Error认证错误
The Node.js driver can fail to connect to a MongoDB instance if the authorization is not configured correctly. If you are using 如果授权配置不正确,Node.js驱动程序可能无法连接到MongoDB实例。如果您使用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进行身份验证,并且驱动程序无法连接,则驱动程序可能会发出类似于以下消息之一的错误消息:
MongoServerError: bad auth : authentication failed
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 you attempt to connect to MongoDB by using 当您尝试使用SCRAM-SHA-256.SCRAM-SHA-256连接到MongoDB时,无效的连接字符串是身份验证问题的最常见原因。
Tip
For more information about connection strings, see the Connection URI section 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. To use a different database for authentication, specify the authSource in the connection string. admin数据库。若要使用其他数据库进行身份验证,请在连接字符串中指定authSource。The following example instructs the driver to use 以下示例指示驱动程序将users as the authentication database:users用作身份验证数据库:
const { MongoClient } = require("mongodb");
const uri = "mongodb://<db_username>:<db_password>@<hostname>:<port>/?authSource=users";
const client = new MongoClient(uri);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. 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.验证您是否已使用正确的用户访问了MongoDB部署。错误中的“消息”一词可以是驱动程序发送的命令。如果您使用的用户没有发送命令的权限,驱动程序可能会生成此错误。
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.还要确保用户对您发送的消息具有适当的权限。MongoDB使用基于角色的访问控制(RBAC)来控制对MongoDB部署的访问。有关如何在MongoDB中配置RBAC的更多信息,请参阅默认MongoDB端口。
Configure Your Firewall配置防火墙
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.防火墙需要有一个开放的端口来与MongoDB实例通信。有关配置防火墙的更多信息,请参阅连接错误部分中的配置防火墙。
Check the Number of Connections检查连接数量
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. MongoClient实例在其连接池中支持最大数量的并发打开连接。您可以配置定义此限制的参数maxPoolSize。默认值为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.maxPoolSize的打开连接数,服务器将等待连接可用。如果此等待时间超过maxIdleTimeMS值,驱动程序将返回错误。
For more information about how connection pooling works, see the Connection Pool Overview in the Connection Pools page.有关连接池工作原理的更多信息,请参阅连接池页面中的连接池概述。
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 当驱动程序无法建立连接时,它可能会挂起,因为尝试访问无法访问的副本集节点需要太长时间。您可以使用connectTimeoutMS setting. To learn more about this setting, see the Timeout Options in the Server manual.connectTimeoutMS设置来限制驱动程序尝试建立连接的时间。要了解有关此设置的更多信息,请参阅服务器手册中的超时选项。
Ensure the 确保connectTimeoutMS setting is not lower than the highest network latency you have for 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.connectTimeoutMS设置不低于该组成员的最高网络延迟。如果其中一个次要成员的延迟为10000毫秒,将connectTimeoutMS设置为9000会阻止驱动程序连接到该成员。
The following example sets 以下示例将connectTimeoutMS to 10000 milliseconds.connectTimeoutMS设置为10000毫秒。
const client = new MongoClient(uri, {
connectTimeoutMS: 10000,
});Client Disconnect While Running Operation运行操作时客户端断开连接
Starting in MongoDB Server version 4.2, the server terminates running operations such as aggregations and find operations if the client disconnects.从MongoDB Server 4.2版本开始,如果客户端断开连接,服务器将终止运行聚合和查找操作等操作。
Other operations, such as write operations, continue to run on the MongoDB Server even if the client disconnects. This behavior can cause data inconsistencies if your application retries the operation after the client disconnects.其他操作,如写操作,即使客户端断开连接,也会继续在MongoDB服务器上运行。如果您的应用程序在客户端断开连接后重试操作,此行为可能会导致数据不一致。
Unexpected Network Behavior意外的网络行为
You might experience unexpected network behavior if the firewall between your application and MongoDB is misconfigured. These firewalls can be overly aggressive in their removal of connections, which can lead to unexpected errors.如果应用程序和MongoDB之间的防火墙配置错误,您可能会遇到意外的网络行为。这些防火墙在删除连接时可能过于激进,这可能会导致意外错误。
Confirm that your firewall exhibits the following behavior:确认您的防火墙显示以下行为:
The firewall sends a防火墙在关闭连接时发送FINpacket when closing a connection, informing the driver that the socket is closed.FIN数据包,通知驱动程序套接字已关闭。The firewall allows keepalive messages.防火墙允许保持活动消息。
Tip
To learn more about keepalive messages, see the keepAlive Connection Option section in the Connection Options page.要了解有关保活消息的更多信息,请参阅连接选项页面中的保活连接选项部分。
Connection String Errors for Replica Sets副本集的连接字符串错误
The connection string passed to the driver must use exact hostnames for the servers, as set in the Replica Set Config. Given the following configuration settings for your replica set, in order for the replica set discovery and failover to work, the driver must have access to 传递给驱动程序的连接字符串必须使用服务器的确切主机名,如副本集配置中所设置的。给定您的副本集的以下配置设置,为了使副本集发现和故障转移工作,驱动程序必须能够访问server1, server2, and server3.server1、server2和server3。
{
"_id": "testSet",
"version": 1,
"protocolVersion": 1,
"members": [
{
"_id": 1,
"host": "server1:31000"
},
{
"_id": 2,
"host": "server2:31001"
},
{
"_id": 3,
"host": "server3:31002"
}
]
}