Docs Home / Node.js Driver / Connect

Specify Connection Options指定连接选项

This section explains the MongoDB connection and authentication options supported by the Node.js driver that you can set within a MongoClientOptions instance.本节解释了Node.js驱动程序支持的MongoDB连接和身份验证选项,您可以在MongoClientOptions实例中设置这些选项。

For more information on setting connection options directly in a connection string, see Connection Strings in the MongoDB Server manual.有关直接在连接字符串中设置连接选项的更多信息,请参阅MongoDB Server手册中的连接字符串

Name名称Accepted Values接受值Default Value默认值Description描述
appNamestringnullSpecifies the app name the driver passes to the server in the client metadata as part of the connection handshake. 指定驱动程序在客户端元数据中传递给服务器的应用程序名称,作为连接握手的一部分。The driver sends the appName value to MongoDB when establishing the connection. This value is recorded in the log file, the slow query logs, and profile collections.在建立连接时,驱动程序将appName值发送到MongoDB。此值记录在日志文件、慢速查询日志和配置文件集合中。
authMechanismstringnullSpecifies the authentication mechanism method to use for connection to the server. If you do not specify a value, the driver uses the default mechanism, either SCRAM-SHA-1 or SCRAM-SHA-256 depending on the server version. 指定用于连接到服务器的身份验证机制方法。如果不指定值,驱动程序将使用默认机制,根据服务器版本,使用SCRAM-SHA-1SCRAM-SHA-256See the Authentication Mechanisms section for available authentication mechanisms.有关可用的身份验证机制,请参阅身份验证机制部分
authMechanismPropertiescomma separated key:value pairs, for example, "opt1:val1,opt2:val2"逗号分隔的键值对,例如"opt1:val1,opt2:val2"nullSpecifies other options provided for authentication, such as the option to enable hostname canonicalization for GSSAPI.指定为身份验证提供的其他选项,例如为GSSAPI启用主机名规范化的选项。
authSourcestringnullSpecifies the database that connections authenticate against.指定连接进行身份验证的数据库。
autoSelectFamilybooleantrueIf set to true, the socket attempts to connect to IPv6 and IPv4 addresses until a connection is established. If available, the driver will select the first IPv6 address.如果设置为true,套接字将尝试连接到IPv6和IPv4地址,直到建立连接。如果可用,驱动程序将选择第一个IPv6地址。
autoSelectFamilyAttemptTimeoutnon-negative integer非负整数nullSpecifies the amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the autoSelectFamily option. If set to a positive integer less than 10, the value 10 is used instead.指定使用autoSelectFamily选项时,在尝试下一个地址之前等待连接尝试完成的时间量(以毫秒为单位)。如果设置为小于10的正整数,则使用值10
compressorscomma separated list of strings, for example, 逗号分隔的字符串列表,例如"snappy,zlib,zstd"nullSpecifies the allowed compression types for wire protocol messages sent to or received from the server. 指定发送到服务器或从服务器接收的有线协议消息的允许压缩类型。See Network Compression for more information.有关更多信息,请参阅网络压缩
connectTimeoutMSnon-negative integer非负整数30000Specifies the amount of time in milliseconds to wait to establish a single TCP socket connection to the server before raising an error. Specifying 0 means your application sets an infinite socket timeout when establishing a socket.指定在引发错误之前等待与服务器建立单个TCP套接字连接的时间量(以毫秒为单位)。指定0意味着您的应用程序在建立套接字时设置了无限套接字超时。
directConnectionbooleanfalseSpecifies whether to force dispatch all operations to the host specified in the connection URI.指定是否强制将所有操作分派到连接URI中指定的主机。
enableUtf8Validationbooleantrue

Specifying true enables UTF-8 validation for the connection. MongoDB throws an error when it attempts to serialize string data that contains invalid UTF-8 characters to BSON. 指定true将启用连接的UTF-8验证。MongoDB在尝试将包含无效UTF-8字符的字符串数据序列化为BSON时抛出错误。This applies to both document keys and document values, this validation adds processing overhead.这适用于文档键和文档值,此验证会增加处理开销。

Specifying false disables UTF-8 validation for the connection. MongoDB does not throw errors when data contains invalid UTF-8 data. If you disable validation, your application avoids the validation processing overhead.指定false将禁用连接的UTF-8验证。当数据包含无效的UTF-8数据时,MongoDB不会抛出错误。如果禁用验证,您的应用程序将避免验证处理开销。 Editing data while validation is disabled can result in loss of data. Disabling UTF-8 validation is a temporary workaround to query or export data only.禁用验证时编辑数据可能会导致数据丢失。禁用UTF-8验证是仅查询或导出数据的临时解决方法。

To learn more about UTF-8 characters, see UTF-8 on Wikipedia.要了解有关UTF-8字符的更多信息,请参阅维基百科上的UTF-8

heartbeatFrequencyMSinteger greater than or equal to 500大于等于500的整数nullSpecifies the interval, in milliseconds, between regular server monitoring checks.指定常规服务器监视检查之间的间隔(以毫秒为单位)。
loadBalancedbooleannullSpecifies whether the driver is connecting to a load balancer.指定驱动程序是否连接到负载平衡器。
localThresholdMSnon-negative integer非负整数15Specifies the size of the latency window, in milliseconds, on round trip time for selecting between suitable servers. Specifying 0 means no wait, meaning the fastest available server.指定往返时间的延迟窗口大小(以毫秒为单位),以便在合适的服务器之间进行选择。指定0表示无需等待,这意味着最快的可用服务器。
maxIdleTimeMSnon-negative integer非负整数0Specifies the amount of time, in milliseconds, a connection can be idle before it's closed. Specifying 0 means no minimum.指定连接在关闭之前可以空闲的时间量(以毫秒为单位)。指定0表示没有最小值。
maxPoolSizenon-negative integer非负整数100Specifies the maximum number of clients or connections the driver can create in its connection pool. This count includes connections in use.指定驱动程序可以在其连接池中创建的最大客户端或连接数。此计数包括正在使用的连接。
maxConnectingnon-negative integer非负整数2Specifies the maximum number of connections a driver's connection pool may be establishing concurrently.指定驱动程序连接池可以同时建立的最大连接数。
maxStalenessSeconds-1, or an integer greater than or equal 90-1或大于等于90的整数nullSpecifies the maximum replication lag, in wall clock time, that a secondary can experience and still be eligible for server selection. Specifying -1 means no maximum.指定辅助服务器可以经历并且仍然有资格选择服务器的最大复制延迟(以挂钟时间为单位)。指定-1表示没有最大值。
minPoolSizenon-negative integer非负整数0Specifies the number of connections the driver creates and maintains in the connection pool even when no operations are occurring. This count includes connections in use.指定驱动程序在连接池中创建和维护的连接数,即使没有进行任何操作。此计数包括正在使用的连接。
proxyHoststringnullSpecifies the SOCKS5 proxy IPv4 address, IPv6 address, or domain name.指定SOCKS5代理IPv4地址、IPv6地址或域名。
proxyPortnon-negative integer非负整数nullSpecifies the TCP port number of the SOCKS5 proxy server. If you set the proxyHost option, the value of this option defaults to 1080.指定SOCKS5代理服务器的TCP端口号。如果设置proxyHost选项,则此选项的值默认为1080
proxyUsernamestringnullSpecifies the username for authentication to the SOCKS5 proxy server. If you set this option to a zero-length string, the driver ignores it.指定用于向SOCKS5代理服务器进行身份验证的用户名。如果将此选项设置为零长度字符串,驱动程序将忽略它。
proxyPasswordstringnullSpecifies the password for authentication to the SOCKS5 proxy server. If you set this option to a zero-length string, the driver ignores it.指定用于向SOCKS5代理服务器进行身份验证的密码。如果将此选项设置为零长度字符串,驱动程序将忽略它。
readConcernLevelstringnullSpecifies the default read concern for the client. See read concern for more information.指定客户端的默认读取关注。有关更多信息,请参阅读取关注
readPreferencestring"primary"Specifies the default read preference for the client (excluding tags). See read preference for more information.指定客户端的默认读取首选项(不包括标记)。有关更多信息,请参阅读取首选项
readPreferenceTagscomma-separated key:value pairs, for example, 逗号分隔的键值对,例如,"dc:ny,rack:1" and "dc:ny can be specified multiple times, each instance of this key is a separate tag set并且"dc:ny可以多次指定,此键的每个实例都是一个单独的标记集null

Specifies the default read preference tags for the client. This option is valid only if the read preference mode is not primary.指定客户端的默认读取首选项标记。仅当读取首选项模式不是主要模式时,此选项才有效。

The driver uses the order of the tags in the URI as the order for the read preference.驱动程序使用URI中标签的顺序作为读取首选项的顺序。

replicaSetstringnullSpecifies the name of the replica set to connect to.指定要连接的副本集的名称。
retryReadsbooleantrueEnables retryable reads.允许可重试的读取。
retryWritesbooleantrueEnables retryable writes.允许可重试的写入。
serverMonitoringModeauto, stream, pollautoSpecifies the monitoring mode that the driver monitors use. When this option is set to auto, the monitoring mode is determined by the environment in which the driver is running. 指定驱动程序监视使用的监视模式。当此选项设置为auto时,监控模式由驱动程序运行的环境决定。The driver uses polling mode in function-as-a-service (FaaS) environments and the streaming mode in other environments.驱动程序在功能即服务(FaaS)环境中使用轮询模式,在其他环境中使用流模式。
serverSelectionTimeoutMSnon-negative integer非负整数30000Specifies the timeout, in milliseconds, to block for server selection before raising an error.指定在引发错误之前阻止服务器选择的超时时间(以毫秒为单位)。
socketTimeoutMSnon-negative integer非负整数0Specifies the amount of time in milliseconds spent attempting to send or receive on a socket before timing out. Specifying 0 means your application sets an infinite socket timeout when establishing a socket.指定超时前在套接字上尝试发送或接收所花费的时间量(以毫秒为单位)。指定0意味着您的应用程序在建立套接字时设置了无限套接字超时。
srvMaxHostsnon-negative integer非负整数0Specifies the maximum number of SRV results to randomly select when initially populating the seedlist or, during SRV polling, adding new hosts to the topology.指定在最初填充种子列表或在SRV轮询期间向拓扑添加新主机时随机选择的最大SRV结果数。
srvServiceNamea valid SRV service name according to RFC 6335根据RFC 6335的有效SRV服务名称"mongodb"Specifies the service name to use for SRV lookup in initial DNS seedlist discovery.指定在初始DNS种子列表发现中用于SRV查找的服务名称。
sslbooleanfalseThe ssl is an alias for the tls option.ssltls选项的别名。
tlsbooleanfalseSpecifies whether TLS is required for connections to the server. 指定连接到服务器是否需要TLS。Using a srvServiceName of "mongodb+srv", or specifying other tls-prefixed options implicitly sets the value of tls to true.使用"mongodb+srv"srvServiceName,或指定其他以tls为前缀的选项,隐式地将tls的值设置为true
tlsAllowInvalidCertificatesbooleanfalseSpecifies whether the driver generates an error when the server's TLS certificate is invalid. Set this option to true for testing purposes only.指定当服务器的TLS证书无效时,驱动程序是否生成错误。将此选项设置为true仅用于测试目的。
tlsAllowInvalidHostnamesbooleanfalseSpecifies whether the driver generates an error when there is a mismatch between the server's hostname and the hostname specified by the TLS certificate. Set this option to true for testing purposes only.指定当服务器的主机名与TLS证书指定的主机名不匹配时,驱动程序是否生成错误。将此选项设置为true仅用于测试目的。
tlsCAFilestringnullSpecifies the path to a file with either a single or bundle of certificate authorities to trust when making a TLS connection. 指定文件的路径,该文件具有在建立TLS连接时要信任的单个或捆绑的证书颁发机构。To learn more about setting this connection option, see the Provide Certificate Filepaths section of the TLS guide.要了解有关设置此连接选项的更多信息,请参阅TLS指南的“提供证书文件路径”部分。
tlsCertificateKeyFilestringnullSpecifies the path to the client certificate file or the client private key file. If you need both, you must concatenate the files. 指定客户端证书文件或客户端私钥文件的路径。如果两者都需要,则必须将文件连接起来。To learn more about setting this connection option, see the Provide Certificate Filepaths section of the TLS guide.要了解有关设置此连接选项的更多信息,请参阅TLS指南的“提供证书文件路径”部分。
tlsCertificateKeyFilePasswordstringnullSpecifies the password to decrypt the client private key to be used for TLS connections.指定解密用于TLS连接的客户端私钥的密码。
tlsInsecurebooleanfalseSpecifies to relax TLS constraints as much as possible, such as allowing invalid certificates or hostname mismatches. Set this option to true for testing purposes only.指定尽可能放宽TLS约束,例如允许无效证书或主机名不匹配。将此选项设置为true仅用于测试目的。
waitQueueTimeoutMSnon-negative integer非负整数0

Specifies the amount of time, in milliseconds, spent attempting to check out a connection from a server's connection pool before timing out.指定在超时之前尝试从服务器的连接池中签出连接所花费的时间量(以毫秒为单位)。

0 signifies no timeout.0表示没有超时。

zlibCompressionLevelinteger between -1 and 9 (inclusive)介于-19(含)之间的整数-1Specifies the level of compression when using zlib to compress wire protocol messages. 指定使用zlib压缩有线协议消息时的压缩级别。-1 signifies the default level, 0 signifies no compression, 1 signifies the fastest speed, and 9 signifies the best compression. -1表示默认级别,0表示无压缩,1表示最快速度,9表示最佳压缩。See Network Compression for more information.有关更多信息,请参阅网络压缩

Connection Time Out Options连接超时选项

Setting设置Description描述
connectTimeoutMS

connectTimeoutMS 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. connectTimeoutMS是一个连接选项,用于设置连接池中的单个连接在超时之前与MongoDB服务器建立TCP连接的时间(以毫秒为单位)。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 that the server waits 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, pass in the maxTimeMS method as an option with a timeout specification to an operation that returns a Cursor:要指定maxTimeMS,请将maxTimeMS方法作为带有超时规范的选项传递给返回Cursor的操作:

const Cursor = collection.distinct('my-key', { maxTimeMS: 50 });

Close Sockets After Connection连接后关闭套接字

If you experience unexpected network behavior or if a MongoDB process fails with an error, you might 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. When a MongoDB process times out, the driver will close the socket. 为确保在这些情况下驱动程序正确关闭插座,请设置socketTimeoutMS选项。当MongoDB进程超时时,驱动程序将关闭套接字。We recommend that you select a value for socketTimeoutMS that is two to three times longer than the expected duration of the slowest operation that your application executes.我们建议您为socketTimeoutMS选择一个值,该值比应用程序执行的最慢操作的预期持续时间长两到三倍。

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()方法链接到一个操作,该操作返回一个游标以设置特定操作的超时。

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);

keepAlive Connection OptionkeepAlive连接选项

The keepAlive connection option specifies whether to enable Transmission Control Protocol (TCP) keepalives on a TCP socket. keepAlive连接选项指定是否在TCP套接字上启用传输控制协议(TCP)保活If you enable keepalives, the driver checks whether the connection is active by sending periodic pings to your MongoDB deployment. This functionality works only if your operating system supports the SO_KEEPALIVE socket option.如果启用keepalives,驱动程序会通过向MongoDB部署发送定期ping来检查连接是否处于活动状态。仅当您的操作系统支持SO_KEEPALIVE套接字选项时,此功能才有效。

The keepAliveInitialDelay option specifies the number of milliseconds that the driver waits before initiating a keepalive.keepAliveInitialDelay选项指定驱动程序在启动保活之前等待的毫秒数。

The 5.3 driver version release deprecated these options. Starting in version 6.0 of the driver, the keepAlive option is permanently set to true, and the keepAliveInitialDelay is set to 300000 milliseconds (300 seconds).5.3驱动程序版本已弃用这些选项。从驱动程序的6.0版本开始,keepAlive选项永久设置为truekeepAliveInitialDelay设置为300000毫秒(300秒)。

Warning

If your firewall ignores or drops the keepalive messages, you might not be able to identify dropped connections.如果您的防火墙忽略或丢弃了保活消息,您可能无法识别丢失的连接。

Additional Information附加信息

To learn more about connection options that you can set within a MongoClientOptions instance, see MongoClientOptions in the API Documentation.要了解有关可以在MongoClientOptions实例中设置的连接选项的更多信息,请参阅API文档中的MongoClientOptions