Overview
本页介绍了Node.js驱动程序中可用的连接选项,并解释了如何将它们应用于MongoDB连接。
如何指定连接选项
The following sections describe how you can specify connection options by using a connection string or a MongoClientOptions object.
使用连接字符串
You can include connection options in a connection string as <name>=<value> pairs. Pass the connection string to the MongoClient constructor. In the following example, the connection string contains the connectTimeoutMS option with a value of 60000 and the tls option with a value of true:
const uriClient = new MongoClient( 'mongodb://localhost:27017/?connectTimeoutMS=60000&tls=true');要了解有关连接字符串选项的更多信息,请参阅 MongoDB 服务器手册中的“连接字符串选项” 。
使用 MongoClientOptions 对象
You can pass a MongoClientOptions object to the MongoClient constructor to configure connection settings in code. Configuring the connection this way makes it easier to change settings at runtime and helps you catch errors during compilation. This approach also provides more configuration options than the connection string.
The following example sets the connectTimeoutMS option to 60000 milliseconds and enables TLS:
const optionsClient = new MongoClient(uri, { connectTimeoutMS: 60000, tls: true,});副本集选项
DirectConnection
指定是否强制将所有操作分派到托管。如果指定此选项,驱动程序将不接受 SRV 连接格式。必须使用标准连接 URI 格式。要了解有关 SRV 连接和标准连接格式的更多信息,请参阅 MongoDB Server 手册中的连接字符串指南。
如果指定多个托管名,则必须将此属性设立为 false。
数据类型: boolean
默认值: false
示例:
const directConnectionUriClient = new MongoClient( 'mongodb://localhost:27017/?directConnection=true');副本集(Replica Set)
要连接的副本集的名称。
数据类型: string
默认值: null
示例:
const replicaSetUriClient = new MongoClient( 'mongodb://localhost:27017/?replicaSet=rs0');DirectConnection
指定是否强制将所有操作分派到托管。如果指定此选项,驱动程序将不接受 SRV 连接格式。必须使用标准连接 URI 格式。要了解有关 SRV 连接和标准连接格式的更多信息,请参阅 MongoDB Server 手册中的连接字符串指南。
如果指定多个托管名,则必须将此属性设立为 false。
数据类型: boolean
默认值: false
示例:
const directConnectionClient = new MongoClient(uri, { directConnection: true,});副本集(Replica Set)
要连接的副本集的名称。
数据类型: string
默认值: null
示例:
const replicaSetClient = new MongoClient(uri, { replicaSet: 'rs0',});TLS 选项
启用 TLS
指定是否需要 TLS 来连接到服务器。如果使用 "mongodb+srv" 模式或指定其他 TLS 选项,则此选项默认为 true。否则,默认为 false。
The ssl option is an alias for the tls option.
数据类型: boolean
默认值: false
示例:
const tlsUriClient = new MongoClient('mongodb://localhost:27017/?tls=true');指定 CA 文件
The tlsCAFile option specifies the path to a file with either a single or bundle of certificate authorities to trust when making a TLS connection. To learn more about setting this option, see the Provide Certificate Filepaths section of the TLS guide.
数据类型: string
默认值: null
示例:
const tlsCaFileUriClient = new MongoClient( 'mongodb://localhost:27017/?tls=true&tlsCAFile=/path/to/ca.pem');指定客户端证书密钥文件
The tlsCertificateKeyFile option specifies 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 option, see the Provide Certificate Filepaths section of the TLS guide.
数据类型: string
默认值: null
示例:
const tlsCertKeyFileUriClient = new MongoClient( 'mongodb://localhost:27017/?tls=true&tlsCertificateKeyFile=/path/to/client.pem');指定客户端证书密钥文件密码
The tlsCertificateKeyFilePassword option specifies the password to decrypt the client private key used for TLS connections.
数据类型: string
默认值: null
示例:
const tlsCertKeyPasswordUriClient = new MongoClient( 'mongodb://localhost:27017/?tls=true&tlsCertificateKeyFile=/path/to/client.pem&tlsCertificateKeyFilePassword=iperLuv60');允许无效证书
The tlsAllowInvalidCertificates option specifies whether the driver generates an error when the server's TLS certificate is invalid. Set this option to true for testing purposes only.
数据类型: boolean
默认值: false
示例:
const tlsAllowInvalidCertsUriClient = new MongoClient( 'mongodb://localhost:27017/?tls=true&tlsAllowInvalidCertificates=true');允许无效主机名
The tlsAllowInvalidHostnames option specifies 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.
数据类型: boolean
默认值: false
示例:
const tlsAllowInvalidHostnamesUriClient = new MongoClient( 'mongodb://localhost:27017/?tls=true&tlsAllowInvalidHostnames=true');放宽TLS限制
The tlsInsecure option relaxes TLS constraints as much as possible, such as allowing invalid certificates or hostname mismatches. Set this option to true for testing purposes only.
数据类型: boolean
默认值: false
示例:
const tlsInsecureUriClient = new MongoClient( 'mongodb://localhost:27017/?tls=true&tlsInsecure=true');启用 TLS
指定是否需要 TLS 来连接到服务器。如果使用 "mongodb+srv" 模式或指定其他 TLS 选项,则此选项默认为 true。否则,默认为 false。
The ssl option is an alias for the tls option.
数据类型: boolean
默认值: false
示例:
const tlsClient = new MongoClient(uri, { tls: true,});指定 CA 文件
The tlsCAFile option specifies the path to a file with either a single or bundle of certificate authorities to trust when making a TLS connection. To learn more about setting this option, see the Provide Certificate Filepaths section of the TLS guide.
数据类型: string
默认值: null
示例:
const tlsCaFileClient = new MongoClient(uri, { tls: true, tlsCAFile: '/path/to/ca.pem',});指定客户端证书密钥文件
The tlsCertificateKeyFile option specifies 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 option, see the Provide Certificate Filepaths section of the TLS guide.
数据类型: string
默认值: null
示例:
const tlsCertKeyFileClient = new MongoClient(uri, { tls: true, tlsCertificateKeyFile: '/path/to/client.pem',});指定客户端证书密钥文件密码
The tlsCertificateKeyFilePassword option specifies the password to decrypt the client private key used for TLS connections.
数据类型: string
默认值: null
示例:
const tlsCertKeyPasswordClient = new MongoClient(uri, { tls: true, tlsCertificateKeyFile: '/path/to/client.pem', tlsCertificateKeyFilePassword: 'iperLuv60',});允许无效证书
The tlsAllowInvalidCertificates option specifies whether the driver generates an error when the server's TLS certificate is invalid. Set this option to true for testing purposes only.
数据类型: boolean
默认值: false
示例:
const tlsAllowInvalidCertsClient = new MongoClient(uri, { tls: true, tlsAllowInvalidCertificates: true,});允许无效主机名
The tlsAllowInvalidHostnames option specifies 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.
数据类型: boolean
默认值: false
示例:
const tlsAllowInvalidHostnamesClient = new MongoClient(uri, { tls: true, tlsAllowInvalidHostnames: true,});放宽TLS限制
The tlsInsecure option relaxes TLS constraints as much as possible, such as allowing invalid certificates or hostname mismatches. Set this option to true for testing purposes only.
数据类型: boolean
默认值: false
示例:
const tlsInsecureClient = new MongoClient(uri, { tls: true, tlsInsecure: true,});有关 TLS 选项的更多信息,请参阅“在连接上启用 TLS”指南。
超时选项
ConnectTimeout
驱动程序在超时前尝试与服务器建立单个 TCP 套接字连接的时间长度。
Data Type: non-negative number
默认值: 30000 毫秒
示例:
const connectTimeoutUriClient = new MongoClient( 'mongodb://localhost:27017/?connectTimeoutMS=60000');SocketTimeout
驱动程序在超时之前尝试在套接字上发送或接收的时间长度。默认值由操作系统设立。
If a MongoDB process fails with an error or the network connection drops, you might not receive confirmation that the driver closed the corresponding socket. To ensure that the driver closes the socket in these cases, set the socketTimeoutMS option. Select a value for socketTimeoutMS that is two to three times longer than the expected duration of your slowest operation.
Data Type: non-negative number
默认值: 0 (无超时)
示例:
const socketTimeoutUriClient = new MongoClient( 'mongodb://localhost:27017/?socketTimeoutMS=60000');ServerSelectionTimeout
驱动程序在超时之前尝试选择服务器的时间长度。
Data Type: non-negative number
默认值: 30000 毫秒
示例:
const serverSelectionTimeoutUriClient = new MongoClient( 'mongodb://localhost:27017/?serverSelectionTimeoutMS=10000');ConnectTimeout
驱动程序在超时前尝试与服务器建立单个 TCP 套接字连接的时间长度。
Data Type: non-negative number
默认值: 30000 毫秒
示例:
const connectTimeoutClient = new MongoClient(uri, { connectTimeoutMS: 60000,});SocketTimeout
驱动程序在超时之前尝试在套接字上发送或接收的时间长度。默认值由操作系统设立。
If a MongoDB process fails with an error or the network connection drops, you might not receive confirmation that the driver closed the corresponding socket. To ensure that the driver closes the socket in these cases, set the socketTimeoutMS option. Select a value for socketTimeoutMS that is two to three times longer than the expected duration of your slowest operation.
Data Type: non-negative number
默认值: 0 (无超时)
示例:
const socketTimeoutClient = new MongoClient(uri, { socketTimeoutMS: 60000,});ServerSelectionTimeout
驱动程序在超时之前尝试选择服务器的时间长度。
Data Type: non-negative number
默认值: 30000 毫秒
示例:
const serverSelectionTimeoutClient = new MongoClient(uri, { serverSelectionTimeoutMS: 10000,});要了解如何限制单个操作的服务器执行时间,请参阅“限制服务器执行时间”指南。
压缩选项
compressors
首选压缩类型(按顺序),用于发送到服务器或从服务器接收的传输协议消息。您可以将“snappy”、“zlib”和“zstd”作为可选的构建时依赖项启用。驱动程序使用服务器支持的第一种压缩类型。
Data Type: comma-separated string
默认值: null
示例:
const compressorsUriClient = new MongoClient( 'mongodb://localhost:27017/?compressors=snappy,zlib,zstd');zlibCompressionLevel
The zlibCompressionLevel option sets the compression level for zlib to use. This option accepts an integer value between -1 and 9:
-1:默认压缩级别。0: 无压缩。1: 速度最快,但压缩最低。9: 压缩最佳,但速度最慢。
数据类型: number between -1 and 9 (inclusive)
默认值: -1
示例:
const zlibLevelUriClient = new MongoClient( 'mongodb://localhost:27017/?compressors=zlib&zlibCompressionLevel=6');compressors
首选压缩类型(按顺序),用于发送到服务器或从服务器接收的传输协议消息。您可以将“snappy”、“zlib”和“zstd”作为可选的构建时依赖项启用。驱动程序使用服务器支持的第一种压缩类型。
Data Type: array of string values
默认值: null
示例:
const compressorsClient = new MongoClient(uri, { compressors: ['snappy', 'zlib', 'zstd'],});zlibCompressionLevel
The zlibCompressionLevel option sets the compression level for zlib to use. This option accepts an integer value between -1 and 9:
-1:默认压缩级别。0: 无压缩。1: 速度最快,但压缩最低。9: 压缩最佳,但速度最慢。
数据类型: number between -1 and 9 (inclusive)
默认值: -1
示例:
const zlibLevelClient = new MongoClient(uri, { compressors: ['zlib'], zlibCompressionLevel: 6,});有关压缩的更多信息,请参阅《压缩网络流量指南》。
连接池选项
maxPoolSize
驱动程序可在其连接池中创建的客户端或连接的最大数量。此计数包括正在使用的连接。
Data Type: non-negative number
默认值: 100
示例:
const maxPoolSizeUriClient = new MongoClient( 'mongodb://localhost:27017/?maxPoolSize=150');minPoolSize
即使没有发生任何操作,驱动程序在连接池中创建并保持的连接数。此计数包括正在使用的连接。
Data Type: non-negative number
默认值: 0
示例:
const minPoolSizeUriClient = new MongoClient( 'mongodb://localhost:27017/?minPoolSize=10');MaxConnectionIdleTime
在驱动程序关闭连接之前,该连接可处于空闲状态的时间长度。
Data Type: non-negative number
默认值: 0 (no limit)
示例:
const maxIdleTimeUriClient = new MongoClient( 'mongodb://localhost:27017/?maxIdleTimeMS=30000');MaxConnecting
The maxConnecting option sets the maximum number of connections the connection pool may establish concurrently.
Data Type: non-negative number
默认值: 2
示例:
const maxConnectingUriClient = new MongoClient( 'mongodb://localhost:27017/?maxConnecting=5');WaitQueueTimeout
驱动程序在超时之前尝试从服务器的连接池检出连接的时间长度。
Data Type: non-negative number
默认值: 0 (无超时)
示例:
const waitQueueTimeoutUriClient = new MongoClient( 'mongodb://localhost:27017/?waitQueueTimeoutMS=2000');maxPoolSize
驱动程序可在其连接池中创建的客户端或连接的最大数量。此计数包括正在使用的连接。
Data Type: non-negative number
默认值: 100
示例:
const maxPoolSizeClient = new MongoClient(uri, { maxPoolSize: 150,});minPoolSize
即使没有发生任何操作,驱动程序在连接池中创建并保持的连接数。此计数包括正在使用的连接。
Data Type: non-negative number
默认值: 0
示例:
const minPoolSizeClient = new MongoClient(uri, { minPoolSize: 10,});MaxConnectionIdleTime
在驱动程序关闭连接之前,该连接可处于空闲状态的时间长度。
Data Type: non-negative number
默认值: 0 (no limit)
示例:
const maxIdleTimeClient = new MongoClient(uri, { maxIdleTimeMS: 30000,});MaxConnecting
The maxConnecting option sets the maximum number of connections the connection pool may establish concurrently.
Data Type: non-negative number
默认值: 2
示例:
const maxConnectingClient = new MongoClient(uri, { maxConnecting: 5,});WaitQueueTimeout
驱动程序在超时之前尝试从服务器的连接池检出连接的时间长度。
Data Type: non-negative number
默认值: 0 (无超时)
示例:
const waitQueueTimeoutClient = new MongoClient(uri, { waitQueueTimeoutMS: 2000,});要了解有关连接池的更多信息,请参阅“使用连接池管理连接”指南。
写关注选项
写关注
写关注(write concern)的 w 组件,请求确认写入操作已传播到指定数量的MongoDB实例。默认值为 "majority" 或 1,具体取决于仲裁节点和投票节点的数量。要学习;了解有关 w 选项的更多信息,请参阅MongoDB Server手册中的写关注。
您还可以在连接字符串中设置以下选项来完成写入操作:
journal:指定驱动程序是否等待服务器将分组提交到磁盘上的日志文件。wtimeoutMS:指定写入操作的时间限制。
要了解更多信息,请参阅 MongoDB 服务器手册中的“写入关注点”部分。
数据类型:
woption:numberorstringjournal选项:booleanwtimeoutMS选项:非负number
默认值:
w选项:1journaloption: depends on thewriteConcernMajorityJournalDefaultreplica set configuration settingwtimeoutMSoption:0(no timeout)
示例:
const writeConcernUriClient = new MongoClient( 'mongodb://localhost:27017/?w=majority&journal=true&wtimeoutMS=1000');写关注
The writeConcern option specifies the level of acknowledgement requested from MongoDB for write operations, including the time limit.
要了解更多信息,请参阅 MongoDB 服务器手册中的“写入关注点”部分。
The MongoClientOptions type also defines top-level w, wtimeoutMS, and journal options. These top-level options are deprecated. Set the properties on the writeConcern option instead, as shown in the example below.
数据类型: WriteConcern or WriteConcernSettings object
默认值: w: 1
示例:
const writeConcernClient = new MongoClient(uri, { writeConcern: { w: 'majority', journal: true, wtimeoutMS: 1000 },});读关注选项
读关注级别
客户端的读关注(read concern)级别。有关更多信息,请参阅MongoDB Server手册中的读关注(read concern)参考。
数据类型: string
默认值: null
示例:
const readConcernLevelUriClient = new MongoClient( 'mongodb://localhost:27017/?readConcernLevel=majority');读关注级别
客户端的读关注(read concern)级别。有关更多信息,请参阅MongoDB Server手册中的读关注(read concern)参考。
数据类型: string
默认值: null
示例:
const readConcernLevelClient = new MongoClient(uri, { readConcernLevel: 'majority',});读取偏好选项
读取偏好
客户端的默认读取偏好(read preference)设置。有关详细信息,请参阅 MongoDB Server 手册中的 读取偏好(read preference)。
数据类型: string
默认值: primary
示例:
const readPreferenceUriClient = new MongoClient( 'mongodb://localhost:27017/?readPreference=secondaryPreferred');readPreferenceTags
The readPreferenceTags option specifies the default read preference tags for the client as comma-separated key:value pairs. 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. To learn more about read preference tags, see tags in the MongoDB Server manual.
Data Type: comma-separated key:value pairs
默认值: null
示例:
const readPreferenceTagsUriClient = new MongoClient( replicaSetUri + '&readPreference=secondaryPreferred&readPreferenceTags=dc:ny,rack:1');maxStalenessSeconds
Max Staleness Seconds 表示从节点(secondary node from replica set)可能出现但仍有资格被选择服务器的最长复制延迟(以挂钟时间为单位)。maxStalenessSeconds 的最小允许值为 90 秒。此选项必须与非主节点读取偏好(read preference)一起使用。
要不设置最大值,请省略此选项,而不是显式设置它。
数据类型: number 大于或等于 90
默认值: null (无上限)
示例:
const maxStalenessUriClient = new MongoClient( replicaSetUri + '&readPreference=secondaryPreferred&maxStalenessSeconds=120');LocalThreshold
服务器资格的延迟窗口。如果服务器的往返时间长于最快服务器的往返时间加上此值,则该服务器没有资格被选中。
Data Type: non-negative number
默认值: 15 毫秒
示例:
const localThresholdUriClient = new MongoClient( 'mongodb://localhost:27017/?localThresholdMS=30');读取偏好
客户端的默认读取偏好(read preference)设置。有关详细信息,请参阅 MongoDB Server 手册中的 读取偏好(read preference)。
数据类型: ReadPreferenceMode or ReadPreference object
默认值: primary
示例:
const readPreferenceClient = new MongoClient(uri, { readPreference: 'secondaryPreferred',});readPreferenceTags
The readPreferenceTags option specifies the default read preference tags for the client. Each tag set is an object that maps tag keys to values. This option is valid only if the read preference mode is not primary. To learn more about read preference tags, see tags in the MongoDB Server manual.
数据类型:标签文档数组
默认值: null
示例:
const readPreferenceTagsClient = new MongoClient(replicaSetUri, { readPreference: 'secondaryPreferred', readPreferenceTags: [{ dc: 'ny', rack: '1' }],});maxStalenessSeconds
Max Staleness Seconds 表示从节点(secondary node from replica set)可能出现但仍有资格被选择服务器的最长复制延迟(以挂钟时间为单位)。maxStalenessSeconds 的最小允许值为 90 秒。此选项必须与非主节点读取偏好(read preference)一起使用。
要不设置最大值,请省略此选项,而不是显式设置它。
数据类型: number 大于或等于 90
默认值: null (无上限)
示例:
const maxStalenessClient = new MongoClient(replicaSetUri, { readPreference: 'secondaryPreferred', maxStalenessSeconds: 120,});LocalThreshold
服务器资格的延迟窗口。如果服务器的往返时间长于最快服务器的往返时间加上此值,则该服务器没有资格被选中。
Data Type: non-negative number
默认值: 15 毫秒
示例:
const localThresholdClient = new MongoClient(uri, { localThresholdMS: 30,});身份验证选项
身份验证机制
驱动程序用于向 MongoDB Server 进行身份验证的机制。如果您未指定身份验证机制,驱动程序将使用 SCRAM-SHA-1 或 SCRAM-SHA-256,具体取决于服务器版本。
要了解有关可用身份验证机制的更多信息,请参阅身份验证机制指南。
数据类型: string
默认值: null (the driver uses SCRAM-SHA-1 or SCRAM-SHA-256 depending on the server version)
示例:
const authMechanismUriClient = new MongoClient( 'mongodb://user:password@localhost:27017/?authSource=admin&authMechanism=SCRAM-SHA-256');身份验证机制属性
The authMechanismProperties option specifies properties for the authentication mechanism set in the authMechanism option, such as the service name for Kerberos (GSSAPI) authentication.
数据类型:以逗号分隔的键值对
默认值: null
示例:
const authMechanismPropertiesUriClient = new MongoClient( 'mongodb://<Kerberos principal>@localhost:27017/?authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:<service name>');authSource
The authSource option specifies the database that contains the user's credentials.
数据类型: string
默认值: null
示例:
const authSourceUriClient = new MongoClient( 'mongodb://user:password@localhost:27017/?authSource=admin');身份验证机制
驱动程序用于向 MongoDB Server 进行身份验证的机制。如果您未指定身份验证机制,驱动程序将使用 SCRAM-SHA-1 或 SCRAM-SHA-256,具体取决于服务器版本。
要了解有关可用身份验证机制的更多信息,请参阅身份验证机制指南。
数据类型: AuthMechanism
默认值: null (the driver uses SCRAM-SHA-1 or SCRAM-SHA-256 depending on the server version)
示例:
const authMechanismClient = new MongoClient( 'mongodb://user:password@localhost:27017/', { authSource: 'admin', authMechanism: 'SCRAM-SHA-256', });身份验证机制属性
The authMechanismProperties option specifies properties for the authentication mechanism set in the authMechanism option, such as the service name for Kerberos (GSSAPI) authentication.
数据类型: AuthMechanismProperties 对象
默认值: null
示例:
const authMechanismPropertiesClient = new MongoClient( 'mongodb://<Kerberos principal>@localhost:27017/', { authMechanism: 'GSSAPI', authMechanismProperties: { SERVICE_NAME: '<service name>', }, });authSource
The authSource option specifies the database that contains the user's credentials.
数据类型: string
默认值: null
示例:
const authSourceClient = new MongoClient( 'mongodb://user:password@localhost:27017/', { authSource: 'admin', });服务器监控选项
心跳频率
服务器监控检查之间的时间间隔。必须大于或等于 500 毫秒。在池化(多线程)模式下,默认值为 10000 毫秒(10 秒);在非池化(单线程)模式下,默认值为 60000 毫秒(60 秒)。
Node.js 驱动程序维护一个连接池,因此驱动程序默认使用连接池模式。
数据类型: number 大于或等于 500
默认值: 10000 毫秒
示例:
const heartbeatFrequencyUriClient = new MongoClient( 'mongodb://localhost:27017/?heartbeatFrequencyMS=10000');服务器监控模式
The serverMonitoringMode option specifies 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 runs. The driver uses polling mode in function-as-a-service (FaaS) environments and the streaming mode in other environments.
数据类型: auto、stream 或 poll
默认值: auto
示例:
const serverMonitoringModeUriClient = new MongoClient( 'mongodb://localhost:27017/?serverMonitoringMode=poll');心跳频率
服务器监控检查之间的时间间隔。必须大于或等于 500 毫秒。在池化(多线程)模式下,默认值为 10000 毫秒(10 秒);在非池化(单线程)模式下,默认值为 60000 毫秒(60 秒)。
Node.js 驱动程序维护一个连接池,因此驱动程序默认使用连接池模式。
数据类型: number 大于或等于 500
默认值: 10000 毫秒
示例:
const heartbeatFrequencyClient = new MongoClient(uri, { heartbeatFrequencyMS: 10000,});服务器监控模式
The serverMonitoringMode option specifies 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 runs. The driver uses polling mode in function-as-a-service (FaaS) environments and the streaming mode in other environments.
数据类型: auto、stream 或 poll
默认值: auto
示例:
const serverMonitoringModeClient = new MongoClient(uri, { serverMonitoringMode: 'poll',});重试选项
retryReads
允许重试读取。
数据类型: boolean
默认值: true
示例:
const retryReadsUriClient = new MongoClient( 'mongodb://localhost:27017/?retryReads=false');retryWrites
启用可重试写入。
数据类型: boolean
默认值: true
示例:
const retryWritesUriClient = new MongoClient( 'mongodb://localhost:27017/?retryWrites=false');最大自适应重试
The maxAdaptiveRetries option sets the maximum number of retries to attempt when the driver encounters overload errors. Specifying 0 disables adaptive retries. This option requires MongoDB Atlas 9.0 or later.
Data Type: non-negative number
默认值: 2
示例:
const maxAdaptiveRetriesUriClient = new MongoClient( 'mongodb://localhost:27017/?maxAdaptiveRetries=2');过载重定向
The enableOverloadRetargeting option specifies whether the driver deprioritizes a server that returns an overload error, reducing the likelihood of retrying on the same overloaded server. This option requires MongoDB Atlas 9.0 or later.
数据类型: boolean
默认值: false
示例:
const overloadRetargetingUriClient = new MongoClient( 'mongodb://localhost:27017/?enableOverloadRetargeting=true');retryReads
允许重试读取。
数据类型: boolean
默认值: true
示例:
const retryReadsClient = new MongoClient(uri, { retryReads: false,});retryWrites
启用可重试写入。
数据类型: boolean
默认值: true
示例:
const retryWritesClient = new MongoClient(uri, { retryWrites: false,});最大自适应重试
The maxAdaptiveRetries option sets the maximum number of retries to attempt when the driver encounters overload errors. Specifying 0 disables adaptive retries. This option requires MongoDB Atlas 9.0 or later.
Data Type: non-negative number
默认值: 2
示例:
const maxAdaptiveRetriesClient = new MongoClient(uri, { maxAdaptiveRetries: 2,});过载重定向
The enableOverloadRetargeting option specifies whether the driver deprioritizes a server that returns an overload error, reducing the likelihood of retrying on the same overloaded server. This option requires MongoDB Atlas 9.0 or later.
数据类型: boolean
默认值: false
示例:
const overloadRetargetingClient = new MongoClient(uri, { enableOverloadRetargeting: true,});注意
智能工作负载管理 (IWM) 中的负载削减
如果带有 SystemOverloadedError 或 RetryableError 标签的错误导致您的应用程序出现故障或出现在您的应用程序日志中,则说明您的集群上可能已启用负载削减 (Load Shedding),并且您的驱动程序可能未升级到支持该功能的版本。我们建议将您的 MongoDB Node.js 驱动程序升级到 7.2 或更高版本。如果您在升级后仍然看到这些错误,可以通过服务器端更改(例如查看您的负载削减配置)或通过应用程序端更改(例如实现自定义错误处理或客户端请求限制)来解决这些错误。根据您的情况,应用程序端更改可能是更可取或必要的。
负载削减 (Load Shedding) 是 IWM 的一项功能,有助于在持续过载期间通过拒绝多余的操作来管理服务器负载。此功能适用于 MongoDB 9.0 及更高版本。
其他选项
ApplicationName
驱动程序在连接握手过程中作为客户端元数据的一部分传递给服务器的应用名称。服务器建立连接后,会将此值打印到 MongoDB 日志中。该值还会记录在慢速查询日志和配置文件集合中。
数据类型: string
默认值: null
示例:
const appNameUriClient = new MongoClient( 'mongodb://localhost:27017/?appName=docsExample');LoadBalanced
指定驱动程序是否正在连接到负载均衡器。仅当满足以下所有条件时,才能将此属性设立为 true:
您仅指定一个托管名
您没有连接到副本集
您没有使用
SrvMaxHosts属性您没有使用
DirectConnection属性
The Node.js driver supports this option only in the connection string. You cannot set it in a MongoClientOptions object.
数据类型: boolean
默认值: false
示例:
const loadBalancedUriClient = new MongoClient( 'mongodb://localhost:27017/?loadBalanced=true');SrvMaxHosts
初始填充种子列表或在 SRV 轮询期间向拓扑结构添加新主机时要随机选择的 SRV 结果的最大数量。
仅当连接字符串模式设立为 ConnectionStringScheme.MongoDBPlusSrv 时才能使用此属性。连接到副本集时无法使用它。
Data Type: non-negative number
默认值: 0 (无限)
示例:
const srvMaxHostsUriClient = new MongoClient( 'mongodb+srv://cluster.example.mongodb.net/?srvMaxHosts=10');srvServiceName
SRV 资源记录的服务名称,驱动程序会检索该服务名称以构建您的种子列表。驱动程序使用该服务名称创建 SRV URI,其格式如下:
_{srvServiceName}._tcp.{hostname}.{domainname}此属性会覆盖发现和轮询中 SRV 查找的默认服务名称。默认值为 "mongodb"。
仅当连接字符串模式设立为 ConnectionStringScheme.MongoDBPlusSrv 时才能使用此属性。连接到副本集时无法使用它。
数据类型: string
默认值: mongodb
示例:
const srvServiceNameUriClient = new MongoClient( 'mongodb+srv://cluster.example.mongodb.net/?srvServiceName=docsExample');自动选择系列
If you set the autoSelectFamily option to true, the socket attempts to connect to IPv6 and IPv4 addresses until a connection is established. If available, the driver selects the first IPv6 address.
数据类型: boolean
默认值: true
示例:
const autoSelectFamilyUriClient = new MongoClient( 'mongodb://localhost:27017/?autoSelectFamily=false');自动选择家庭尝试超时
The autoSelectFamilyAttemptTimeout option specifies 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 you set a positive integer less than 10, the driver uses 10 instead.
Data Type: non-negative number
默认值: null
示例:
const autoSelectFamilyAttemptTimeoutUriClient = new MongoClient( 'mongodb://localhost:27017/?autoSelectFamilyAttemptTimeout=300');UTF-8 验证
The enableUtf8Validation option specifies whether the driver validates UTF-8 characters when it deserializes BSON documents from MongoDB. If you enable validation, the driver throws a BSONError when it reads data that contains invalid UTF-8 characters. Disable UTF-8 validation only as a temporary workaround to query or export data.
要学习;了解有关 UTF-8 字符的更多信息,请参阅维基百科上的 UTF-8。
数据类型: boolean
默认值: true
示例:
const utf8ValidationUriClient = new MongoClient( 'mongodb://localhost:27017/?enableUtf8Validation=false');SOCKS5 代理
You can route connections through a SOCKS5 proxy by setting the proxyHost option to the proxy's IPv4 address, IPv6 address, or domain name. The proxyPort option specifies the TCP port number of the proxy server. To authenticate to the proxy server, set the proxyUsername and proxyPassword options. If you omit the proxyPort option, the driver uses 1080. If you set one of the proxyUsername or proxyPassword options, you must set both. To learn more, see Enable SOCKS5 Proxy Support.
数据类型:
stringfor theproxyHost,proxyUsername, andproxyPasswordoptionsnon-negative
numberfor theproxyPortoption
默认值: null 适用于所有四种选项
示例:
const proxyUriClient = new MongoClient( 'mongodb://localhost:27017/?proxyHost=proxy.example.com&proxyPort=4040&proxyUsername=proxyUser&proxyPassword=docsExample');ApplicationName
驱动程序在连接握手过程中作为客户端元数据的一部分传递给服务器的应用名称。服务器建立连接后,会将此值打印到 MongoDB 日志中。该值还会记录在慢速查询日志和配置文件集合中。
数据类型: string
默认值: null
示例:
const appNameClient = new MongoClient(uri, { appName: 'docsExample',});SrvMaxHosts
初始填充种子列表或在 SRV 轮询期间向拓扑结构添加新主机时要随机选择的 SRV 结果的最大数量。
仅当连接字符串模式设立为 ConnectionStringScheme.MongoDBPlusSrv 时才能使用此属性。连接到副本集时无法使用它。
Data Type: non-negative number
默认值: 0 (无限)
示例:
const srvMaxHostsClient = new MongoClient( 'mongodb+srv://cluster.example.mongodb.net/', { srvMaxHosts: 10, });srvServiceName
SRV 资源记录的服务名称,驱动程序会检索该服务名称以构建您的种子列表。驱动程序使用该服务名称创建 SRV URI,其格式如下:
_{srvServiceName}._tcp.{hostname}.{domainname}此属性会覆盖发现和轮询中 SRV 查找的默认服务名称。默认值为 "mongodb"。
仅当连接字符串模式设立为 ConnectionStringScheme.MongoDBPlusSrv 时才能使用此属性。连接到副本集时无法使用它。
数据类型: string
默认值: mongodb
示例:
const srvServiceNameClient = new MongoClient( 'mongodb+srv://cluster.example.mongodb.net/', { srvServiceName: 'docsExample', });自动选择系列
If you set the autoSelectFamily option to true, the socket attempts to connect to IPv6 and IPv4 addresses until a connection is established. If available, the driver selects the first IPv6 address.
数据类型: boolean
默认值: true
示例:
const autoSelectFamilyClient = new MongoClient(uri, { autoSelectFamily: false,});自动选择家庭尝试超时
The autoSelectFamilyAttemptTimeout option specifies 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 you set a positive integer less than 10, the driver uses 10 instead.
Data Type: non-negative number
默认值: null
示例:
const autoSelectFamilyAttemptTimeoutClient = new MongoClient(uri, { autoSelectFamilyAttemptTimeout: 300,});UTF-8 验证
The enableUtf8Validation option specifies whether the driver validates UTF-8 characters when it deserializes BSON documents from MongoDB. If you enable validation, the driver throws a BSONError when it reads data that contains invalid UTF-8 characters. Disable UTF-8 validation only as a temporary workaround to query or export data.
要学习;了解有关 UTF-8 字符的更多信息,请参阅维基百科上的 UTF-8。
数据类型: boolean
默认值: true
示例:
const utf8ValidationClient = new MongoClient(uri, { enableUtf8Validation: false,});SOCKS5 代理
You can route connections through a SOCKS5 proxy by setting the proxyHost option to the proxy's IPv4 address, IPv6 address, or domain name. The proxyPort option specifies the TCP port number of the proxy server. To authenticate to the proxy server, set the proxyUsername and proxyPassword options. If you omit the proxyPort option, the driver uses 1080. If you set one of the proxyUsername or proxyPassword options, you must set both. To learn more, see Enable SOCKS5 Proxy Support.
数据类型:
stringfor theproxyHost,proxyUsername, andproxyPasswordoptionsnon-negative
numberfor theproxyPortoption
默认值: null 适用于所有四种选项
示例:
const proxyClient = new MongoClient(uri, { proxyHost: 'proxy.example.com', proxyPort: 4040, proxyUsername: 'proxyUser', proxyPassword: 'docsExample',});运行时适配器
(Experimental) The runtimeAdapters option specifies custom implementations of core Node.js APIs. Use this option to run the driver in restricted environments or in alternative runtimes incompatible with Node.js. This option is not supported in a connection string.
数据类型: RuntimeAdapters 对象
默认值: null
示例:
const runtimeAdaptersClient = new MongoClient(uri, { runtimeAdapters: { os: { arch: () => 'x64', platform: () => 'linux', release: () => '5.4.0', type: () => 'Linux', }, },});保持存活初始延迟
The keepAliveInitialDelay option specifies the number of milliseconds that the driver waits before initiating a Transmission Control Protocol (TCP) keepalive on a socket. When the driver sends TCP keepalives, it 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. This option is not supported in a connection string.
Driver version 5.3 deprecated the keepAlive option. As of driver version 6.0, the driver always sets keepAlive to true.
警告
如果您的防火墙忽略或删除了 keepalive 消息,您可能无法识别删除的连接。
Data Type: non-negative number
默认值: 120000 milliseconds (120 seconds)
更多信息
要查看所有可用设置,请参阅MongoClientOptions。 API文档。
要了解有关连接字符串选项的更多信息,请参阅 MongoDB 服务器手册中的“连接字符串选项” 。