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.
For more information on setting connection options directly in a connection string, see Connection Strings in the MongoDB Server manual.
Name | Accepted Values | Default Value | Description |
---|---|---|---|
appName | string |
| Specifies the app name the driver passes to the server in the client
metadata as part of the connection handshake. The driver sends the
|
authMechanism | string |
| Specifies 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 |
authMechanismProperties | comma separated key:value pairs, for example, "opt1:val1,opt2:val2" |
| Specifies other options provided for authentication, such as the option to enable hostname canonicalization for GSSAPI. |
authSource | string |
| Specifies the database that connections authenticate against. |
autoSelectFamily | boolean |
| If set to |
autoSelectFamilyAttemptTimeout | non-negative integer |
| Specifies the amount of time in milliseconds to wait for a connection
attempt to finish before trying the next address when using the
|
compressors | comma separated list of strings, for example, "snappy,zlib,zstd" |
| Specifies the allowed compression types for wire protocol messages sent to or received from the server. See Network Compression for more information. |
connectTimeoutMS | non-negative integer |
| Specifies the amount of time in milliseconds to wait to establish a single TCP
socket connection to the server before raising an error. Specifying
|
directConnection | boolean |
| Specifies whether to force dispatch all operations to the host specified in the connection URI. |
enableUtf8Validation | boolean |
| Specifying Specifying You can also set UTF-8 validation in your Node.js code. To learn more about UTF-8 characters, see UTF-8 on Wikipedia. |
heartbeatFrequencyMS | integer greater than or equal to 500 |
| Specifies the interval, in milliseconds, between regular server monitoring checks. |
loadBalanced | boolean |
| Specifies whether the driver is connecting to a load balancer. |
localThresholdMS | non-negative integer |
| Specifies the size of the latency window, in milliseconds, on round trip time for
selecting between suitable servers. Specifying |
maxIdleTimeMS | non-negative integer |
| Specifies the amount of time, in milliseconds, a connection can be idle before it's closed.
Specifying |
maxPoolSize | non-negative integer |
| Specifies the maximum number of clients or connections the driver can create in its connection pool. This count includes connections in use. |
maxConnecting | non-negative integer |
| Specifies the maximum number of connections a driver's connection pool may be establishing concurrently. |
maxStalenessSeconds | -1, or an integer greater than or equal 90 |
| Specifies the maximum replication lag, in wall clock time, that
a secondary can experience and still be eligible for server selection.
Specifying |
minPoolSize | non-negative integer |
| Specifies 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. |
proxyHost | string |
| Specifies the SOCKS5 proxy IPv4 address, IPv6 address, or domain name. |
proxyPort | non-negative integer |
| Specifies the TCP port number of the SOCKS5 proxy server. If you
set the |
proxyUsername | string |
| Specifies the username for authentication to the SOCKS5 proxy server. If you set this option to a zero-length string, the driver ignores it. |
proxyPassword | string |
| Specifies the password for authentication to the SOCKS5 proxy server. If you set this option to a zero-length string, the driver ignores it. |
readConcernLevel | string |
| Specifies the default read concern for the client. See read concern for more information. |
readPreference | string |
| Specifies the default read preference for the client (excluding tags). See read preference for more information. |
readPreferenceTags | comma-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 |
| 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. |
replicaSet | string |
| Specifies the name of the replica set to connect to. |
retryReads | boolean |
| Enables retryable reads. |
retryWrites | boolean |
| Enables retryable writes. |
serverMonitoringMode |
|
| Specifies the monitoring mode that the driver monitors use. When
this option is set to |
serverSelectionTimeoutMS | non-negative integer |
| Specifies the timeout, in milliseconds, to block for server selection before raising an error. |
socketTimeoutMS | non-negative integer |
| Specifies the amount of time in milliseconds spent attempting to send or receive
on a socket before timing out. Specifying |
srvMaxHosts | non-negative integer |
| Specifies the maximum number of SRV results to randomly select when initially populating the seedlist or, during SRV polling, adding new hosts to the topology. |
srvServiceName | a valid SRV service name according to RFC 6335 |
| Specifies the service name to use for SRV lookup in initial DNS seedlist discovery. |
ssl | boolean |
| The |
tls | boolean |
| Specifies whether TLS is required for connections to the server.
Using a |
tlsAllowInvalidCertificates | boolean |
| Specifies whether the driver generates an error when the server's
TLS certificate is invalid. Set this option to |
tlsAllowInvalidHostnames | boolean |
| 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 |
tlsCAFile | string |
| 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 connection option, see the Provide Certificate Filepaths section of the TLS guide. |
tlsCertificateKeyFile | string |
| 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 connection option, see the Provide Certificate Filepaths section of the TLS guide. |
tlsCertificateKeyFilePassword | string |
| Specifies the password to decrypt the client private key to be used for TLS connections. |
tlsInsecure | boolean |
| Specifies to relax TLS constraints as much as possible, such as
allowing invalid certificates or hostname mismatches. Set this option
to |
waitQueueTimeoutMS | non-negative integer |
| Specifies the amount of time, in milliseconds, spent attempting to check out a connection from a server's connection pool before timing out.
|
zlibCompressionLevel | integer between |
| Specifies the level of compression when using zlib to compress wire
protocol messages. |
Connection Time Out Options
Setting | Description |
---|---|
connectTimeoutMS |
Default: 30000 |
socketTimeoutMS |
|
maxTimeMS | maxTimeMS
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 |
To specify the optional settings for your MongoClient
, declare one or
more available settings in the options
object of the constructor as
follows:
const client = new MongoClient(uri, { connectTimeoutMS: <integer value>, socketTimeoutMS: <integer value> });
To see all the available settings, see the MongoClientOptions API Documentation.
To specify maxTimeMS
, pass in the maxTimeMS
method as an option with a timeout
specification to an operation that returns a 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.
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. 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.
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.
The following example shows how you can chain the maxTimeMS()
method
to an operation that returns a Cursor
:
// Execute a find command await collection .find({ $where: "sleep(100) || true" }) .maxTimeMS(50);
keepAlive Connection Option
The keepAlive
connection option specifies whether to enable
Transmission Control Protocol (TCP) keepalives on a TCP socket. 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.
The keepAliveInitialDelay
option specifies the number of
milliseconds that the driver waits before initiating a keepalive.
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).
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.