Docs HomeNode.js

FAQ

This page contains frequently asked questions and their corresponding answers.此页面包含常见问题及其相应的答案。

Tip

If you can't find an answer to your problem on this page, see the Issues & Help page for next steps and more resources.如果在此页面上找不到问题的答案,请参阅问题和帮助页面以了解下一步的步骤和更多资源。

Why Am I Getting Errors While Connecting to MongoDB?为什么我在连接MongoDB时出错?

If you have trouble connecting to a MongoDB deployment, see the Connection Troubleshooting Guide for possible solutions.如果您在连接到MongoDB部署时遇到问题,请参阅连接疑难解答指南以了解可能的解决方案。

How Does Connection Pooling Work in the Node Driver?连接池如何在节点驱动程序中工作?

Every MongoClient instance has a built-in connection pool for each server in your MongoDB topology. 每个MongoClient实例都有一个内置的连接池,用于MongoDB拓扑中的每个服务器。Connection pools open sockets on demand to support concurrent requests to MongoDB in your application.连接池根据需要打开套接字,以支持对应用程序中MongoDB的并发请求。

The maximum size of each connection pool is set by the maxPoolSize option, which defaults to 100. 每个连接池的最大大小由maxPoolSize选项设置,默认值为100If the number of in-use connections to a server reaches the value of maxPoolSize, the next request to that server will wait until a connection becomes available.如果与服务器的使用中连接数达到maxPoolSize值,则对该服务器的下一个请求将等待,直到连接可用。

In addition to the sockets needed to support your application's requests, each MongoClient instance opens two additional sockets per server in your MongoDB topology for monitoring the server's state. 除了支持应用程序请求所需的套接字之外,每个MongoClient实例在MongoDB拓扑中为每台服务器打开两个额外的套接字,用于监控服务器的状态。For example, a client connected to a three-node replica set opens six monitoring sockets. 例如,连接到三节点复制副本集的客户端打开六个监视套接字。If the application uses the default setting for maxPoolSize and only queries the primary (default) node, then there can be at most 106 total connections in the connection pool. 如果应用程序使用maxPoolSize的默认设置,并且只查询主(默认)节点,那么连接池中最多可以有106个连接。If the application uses a read preference to query the secondary nodes, those connection pools grow and there can be 306 total connections.如果应用程序使用读取首选项来查询辅助节点,则这些连接池会增长,并且总共可以有306个连接。

To support high numbers of concurrent MongoDB requests within one process, you can increase maxPoolSize.为了在一个进程中支持大量并发的MongoDB请求,可以增加maxPoolSize

Connection pools are rate-limited. 连接池受速率限制。The maxConnecting option determines the number of connections that the pool can create in parallel at any time. maxConnecting选项确定池可以在任何时候并行创建的连接数。For example, if the value of maxConnecting is 2, the third request that attempts to concurrently check out a connection succeeds only when one the following cases occurs:例如,如果maxConnecting的值为2,则只有在出现以下情况之一时,尝试同时签出连接的第三个请求才会成功:

  • The connection pool finishes creating a connection and there are fewer than maxPoolSize connections in the pool.连接池完成创建连接,并且池中的连接数少于maxPoolSize
  • An existing connection is checked back into the pool.将现有连接签回池中。
  • The driver's ability to reuse existing connections improves due to rate-limits on connection creation.由于连接创建的速率限制,驱动程序重用现有连接的能力得到了提高。

You can set the minimum number of concurrent connections to each server with the minPoolSize option, which defaults to 0. 您可以使用minPoolSize选项设置到每个服务器的最小并发连接数,该选项默认为0The driver initializes the connection pool with this number of sockets. 驱动程序使用此数量的套接字初始化连接池。If sockets are closed, causing the total number of sockets (both in use and idle) to drop below the minimum, more sockets are opened until the minimum is reached.如果套接字关闭,导致套接字总数(处于使用和空闲状态)降至最低值以下,则会打开更多套接字,直到达到最低值。

You can set the maximum number of milliseconds that a connection can remain idle in the pool by setting the maxIdleTimeMS option. 通过设置maxIdleTimeMS选项,可以设置连接在池中保持空闲的最大毫秒数。Once a connection has been idle for maxIdleTimeMS, the connection pool removes and replaces it. 一旦连接空闲了maxIdleTimeMS,连接池就会删除并替换它。This option defaults to 0 (no limit).此选项默认为0(无限制)。

The following default configuration for a MongoClient works for most applications:MongoClient的以下默认配置适用于大多数应用程序:

const client = new MongoClient("<connection string>");

MongoClient supports multiple concurrent requests. MongoClient支持多个并发请求。For each process, create a client and reuse it for all operations in a process. This practice is more efficient than creating a client for each request.对于每个流程,创建一个客户端并将其用于流程中的所有操作。这种做法比为每个请求创建一个客户端更有效。

The driver does not limit the number of requests that can wait for sockets to become available, and it is the application's responsibility to limit the size of its pool to bound queuing during a load spike. 驱动程序不限制可以等待套接字可用的请求数量,应用程序有责任在负载高峰期间将其池的大小限制为绑定队列。Requests wait for the amount of time specified in the waitQueueTimeoutMS option, which defaults to 0 (no limit).请求等待waitQueueTimeoutMS选项中指定的时间,该选项默认为0(无限制)。

A request that waits more than the length of time defined by waitQueueTimeoutMS for a socket raises a connection error. 等待套接字的时间超过waitQueueTimeoutMS定义的时间长度的请求会引发连接错误。Use this option if it is more important to bound the duration of operations during a load spike than it is to complete every operation.如果在负载峰值期间绑定操作的持续时间比完成每个操作更重要,请使用此选项。

When MongoClient.close() is called by any request, the driver closes all idle sockets and closes all sockets that are in use as they are returned to the pool. 当任何请求调用MongoClient.close()时,驱动程序会关闭所有空闲的套接字,并在返回到池时关闭所有正在使用的套接字。Calling MongoClient.close() closes only inactive sockets, so you cannot interrupt or terminate any ongoing operations by using this method. 调用MongoClient.close()只关闭不活动的套接字,因此不能使用此方法中断或终止任何正在进行的操作。The driver closes these sockets only when the process completes.只有当进程完成时,驱动程序才会关闭这些套接字。

What Is the Difference Between "connectTimeoutMS", "socketTimeoutMS" and "maxTimeMS"?"connectTimeoutMS""socketTimeoutMS""maxTimeMS"之间的区别是什么?

Setting设置Description描述
connectTimeoutMSconnectTimeoutMS is a connection option that sets the time, in milliseconds, for an individual connection from your connection pool to establish a TCP connection to the MongoDB server before timing out. 是一个连接选项,用于设置连接池中的单个连接在超时之前与MongoDB服务器建立TCP连接的时间(以毫秒为单位)。
Tip
To modify the allowed time for MongoClient.connect to establish a connection to a MongoDB server, use the serverSelectionTimeoutMS option instead. 要修改MongoClient.connect与MongoDB服务器建立连接的允许时间,请使用serverSelectionTimeoutMS选项。
Default:默认值: 30000
socketTimeoutMSsocketTimeoutMS specifies the amount of time the driver waits for an inactive socket before closing it. 指定驱动程序在关闭非活动套接字之前等待该套接字的时间。The default value is to never time out the socket. 默认值是从不使套接字超时。This option applies only to sockets that have already been connected.此选项仅适用于已连接的套接字。
maxTimeMSmaxTimeMS specifies the maximum amount of time the server should wait for an operation to complete after it has reached the server. 指定服务器在操作到达服务器后等待操作完成的最长时间。If an operation runs over the specified time limit, it returns a timeout error. 如果操作运行超过指定的时间限制,则会返回超时错误。You can pass maxTimeMS only to an individual operation or to a cursor.您只能将maxTimeMS传递给单个操作或游标。

To specify the optional settings for your MongoClient, declare one or more available settings in the options object of the constructor as follows:要指定MongoClient的可选设置,请在构造函数的options对象中声明一个或多个可用设置,如下所示:

const client = new MongoClient(uri, {
connectTimeoutMS: <integer value>,
socketTimeoutMS: <integer value>
});

To see all the available settings, see the MongoClientOptions API Documentation.要查看所有可用的设置,请参阅MongoClientOptions API文档。

To specify maxTimeMS, chain the maxTimeMS() method with a timeout specification to an operation that returns a Cursor:要指定maxTimeMS,请将带有超时规范的maxTimeMS()方法链接到返回Cursor的操作:

const cursor = myColl.find({}).maxTimeMS(50);

What Happens to Running Operations If the Client Disconnects?如果客户端断开连接,运行操作会发生什么?

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版本开始,如果客户端断开连接,服务器将终止正在运行的操作,如聚合和查找操作。To see a full list of operations affected by this behavior, see the Server version 4.2 release notes in the Server manual.要查看受此行为影响的操作的完整列表,请参阅服务器手册中的服务器4.2版发行说明

Other operations, such as write operations, continue to run on the MongoDB Server even if the client disconnects. 其他操作,如写操作,即使客户端断开连接,也会继续在MongoDB服务器上运行。This behavior can cause data inconsistencies if your application retries the operation after the client disconnects.如果应用程序在客户端断开连接后重试该操作,则这种行为可能会导致数据不一致。

How Can I Confirm That the Driver Closed Unusable Sockets?如何确认驱动程序关闭了不可用的套接字?

If you experience unexpected network behavior or if a MongoDB process fails with an error, you may not receive confirmation that the driver correctly closed the corresponding socket.如果您遇到意外的网络行为,或者MongoDB进程出现错误而失败,您可能无法收到驱动程序正确关闭相应套接字的确认。

To make sure that the driver correctly closes the socket in these cases, set the socketTimeoutMS option. 在这些情况下,要确保驱动程序正确关闭套接字,请设置socketTimeoutMS选项。When a MongoDB process times out, the driver will close the socket. 当MongoDB进程超时时,驱动程序将关闭套接字。We recommend that you select a value for socketTimeoutMS that is two to three times as long as the expected duration of the slowest operation that your application executes.我们建议您为socketTimeoutMS选择一个值,该值是应用程序执行的最慢操作的预期持续时间的两到三倍。

How Can I Prevent Sockets From Timing Out Before They Become Active?如何防止套接字在激活之前超时?

Having a large connection pool does not always reduce reconnection requests. 拥有一个大的连接池并不总能减少重新连接请求。Consider the following example:考虑以下示例:

An application has a connection pool size of 5 sockets and has the socketTimeoutMS option set to 5000 milliseconds. 应用程序的连接池大小为5个套接字,并将socketTimeoutMS选项设置为5000毫秒。Operations occur, on average, every 3000 milliseconds, and reconnection requests are frequent. 操作平均每3000毫秒发生一次,并且重新连接请求很频繁。Each socket times out after 5000 milliseconds, which means that all sockets must do something during those 5000 milliseconds to avoid closing.每个套接字在5000毫秒后超时,这意味着所有套接字都必须在这5000毫秒内做一些事情以避免关闭。

One message every 3000 milliseconds is not enough to keep the sockets active, so several of the sockets will time out after 5000 milliseconds. 每3000毫秒一条消息不足以保持套接字处于活动状态,因此几个套接字将在5000毫秒后超时。To avoid excessive socket timeouts, reduce the number of connections that the driver can maintain in the connection pool by specifying the maxPoolSize option.为了避免过度的套接字超时,请通过指定maxPoolSize选项来减少驱动程序可以在连接池中维护的连接数。

To specify the optional maxPoolSize setting for your MongoClient, declare it in the options object of the constructor as follows:要为MongoClient指定可选的maxPoolSize设置,请在构造函数的options对象中声明如下:

const client = new MongoClient(uri, {
maxPoolSize: <integer value>,
});

What Does a Value of "0" mean for "connectTimeoutMS" and "socketTimeoutMS"?"0""connectTimeoutMS""socketTimeoutMS"意味着什么?

If you set the value of connectTimeoutMS or socketTimeoutMS to 0, your application will use the operating system's default socket timeout value.如果将connectTimeoutMSsocketTimeoutMS的值设置为0,则应用程序将使用操作系统的默认套接字超时值。

How Can I Prevent Long-Running Operations From Slowing Down the Server?如何防止长时间运行的操作降低服务器速度?

You can prevent long-running operations from slowing down the server by specifying a timeout value. 通过指定超时值,可以防止长时间运行的操作降低服务器速度。You can chain the maxTimeMS() method to an operation that returns a Cursor to set a timeout on a specific action.您可以将maxTimeMS()方法链接到一个操作,该操作返回一个Cursor来设置特定操作的超时。

The following example shows how you can chain the maxTimeMS() method to an operation that returns a Cursor:以下示例显示如何将maxTimeMS()方法链接到返回Cursor的操作:

// Execute a find command
await collection
.find({ $where: "sleep(100) || true" })
.maxTimeMS(50);

What Does the "keepAlive" Setting Do?"keepAlive"设置的作用是什么?

keepAlive is a connection-setting that sets the number of milliseconds to wait before initiating a TLS keepAlive on a TCP Socket. keepAlive是一个连接设置,用于设置在TCP套接字上启动TLS keepAliive之前等待的毫秒数。The keepAlive option will keep a socket alive by sending periodic probes to MongoDB. However, this only works if the operating system supports SO_KEEPALIVE .keepAlive选项将通过向MongoDB发送定期探测来保持套接字的活动状态。但是,只有当操作系统支持SO_KEEPALIVE时,这才有效。

This setting is deprecated in v5.3 of the Node.js driver and later.Node.js驱动程序的v5.3及更高版本不赞成使用此设置。

Warning

If a firewall ignores or drops the keepAlive packets this may not work如果防火墙忽略或丢弃keepAlive数据包,这可能不起作用

What Can I Do If I'm Experiencing Unexpected Network Behavior?如果我正在经历意外的网络行为,我该怎么办?

Internal firewalls that exist between application servers and MongoDB are often misconfigured and are overly aggressive in their removal of socket connections.应用程序服务器和MongoDB之间存在的内部防火墙经常配置错误,并且在删除套接字连接时过于激进。

If you experience unexpected network behavior, here are some things to check:如果您遇到意外的网络行为,以下是一些需要检查的事项:

  1. The firewall should send a FIN packet when closing a socket, allowing the driver to detect that the socket is closed.防火墙应在关闭套接字时发送FIN packet,使驱动程序能够检测到套接字已关闭。
  2. The firewall should allow keepAlive probes.防火墙应允许keepAlive探测。

How Can I Prevent a Slow Operation From Delaying Other Operations?如何防止慢速操作延迟其他操作?

When you use the same MongoClient instance to run multiple MongoDB operations concurrently, a slow operation can cause delays to other operations. 当您使用同一个MongoClient实例同时运行多个MongoDB操作时,一个缓慢的操作可能会导致其他操作的延迟。Slow operations keep a connection to MongoDB occupied, which can cause other operations to wait until an additional connection becomes available.慢速操作会占用与MongoDB的连接,这可能会导致其他操作等待其他连接可用。

If you suspect that slow MongoDB operations are causing delays, you can check the performance of all in-progress operations by using the following methods:如果怀疑MongoDB操作缓慢导致延迟,可以使用以下方法检查所有正在进行的操作的性能:

  • Enable the database profiler on your deployment. 在部署中启用数据库探查器。To learn more, see Database Profiler in the Server manual.要了解更多信息,请参阅服务器手册中的数据库探察器
  • Run the db.currentOp() MongoDB Shell command. 运行db.currentOp()MongoDB Shell命令。To learn more, see the db.currentOp() documentation in the Server manual.要了解更多信息,请参阅服务器手册中的db.currentOp()文档。
  • Enable connection pool monitoring. To learn more, see Connection Pool Monitoring.启用连接池监视。要了解更多信息,请参阅连接池监控

After you determine which operations are causing delays, try to improve the performance of these operations. 确定哪些操作导致延迟后,请尝试提高这些操作的性能。Read the Best Practices Guide for MongoDB Performance for possible solutions.阅读MongoDB性能最佳实践指南,了解可能的解决方案。

If you implement performance best practices but still experience delays, you can modify your connection settings to increase the size of the connection pool. 如果您实现了性能最佳做法,但仍然遇到延迟,则可以修改连接设置以增加连接池的大小。A connection pool is the group of connections to the server that the driver maintains at any time.连接池是驱动程序随时维护的与服务器的连接组。

To specify the maximum size of a connection pool, you can set the maxPoolSize option in the connection options for your MongoClient instance. 要指定连接池的最大大小,可以在MongoClient实例的连接选项中设置maxPoolSize选项。The default value of maxPoolSize is 100. If the number of in-use connections to a server reaches maxPoolSize, the next operation sent to the server pauses until a connection to the driver becomes available. maxPoolSize的默认值为100。如果与服务器的使用中连接数达到maxPoolSize,则发送到服务器的下一个操作将暂停,直到与驱动程序的连接可用为止。The following code sets maxPoolSize to 150 when creating a new MongoClient:以下代码在创建新的MongoClient时将maxPoolSize设置为150

const client = new MongoClient(uri, { maxPoolSize: 150 });
Tip

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

How Can I Ensure My Connection String Is Valid for a Replica Set?如何确保我的连接字符串对副本集有效?

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 should be able to reach server1, server2, and server3.给定副本集的以下配置设置,为了使副本集发现和故障切换工作,驱动程序应该能够访问server1server2server3

{
"_id": "testSet",
"version": 1,
"protocolVersion": 1,
"members": [
{
"_id": 1,
"host": "server1:31000"
},
{
"_id": 2,
"host": "server2:31001"
},
{
"_id": 3,
"host": "server3:31002"
}
]
}

If you are unable to find the answer to your question here, try our forums and support channels listed in the Issues and Help section.如果您无法在此处找到问题的答案,请尝试问题和帮助部分列出的论坛和支持渠道。