Global

Methods

getCursor(changeStream, callback, oldCursor)

Safely provides a cursor across resume attempts

Name Type Description
changeStream ChangeStream

the parent ChangeStream

callback function

gets the cursor or error

oldCursor ChangeStreamCursor optional

when resuming from an error, carry over options from previous cursor

processResumeQueue(changeStream, err)

Drain the resume queue when a new has become available

Name Type Description
changeStream ChangeStream

the parent ChangeStream

Name Type Description
cursor ChangeStreamCursor nullable

the new cursor

err Error optional

error getting a new cursor

Type Definitions

AutoEncryptionOptions

Properties:
Name Type Argument Description
keyVaultClient MongoClient <optional>

A MongoClient used to fetch keys from a key vault

keyVaultNamespace string <optional>

The namespace where keys are stored in the key vault

kmsProviders object <optional>

Configuration options that are used by specific KMS providers during key generation, encryption, and decryption.

schemaMap object <optional>

A map of namespaces to a local JSON schema for encryption

NOTE: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server.
It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted.
Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption.
Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.

options object <optional>

An optional hook to catch logging messages from the underlying encryption engine

extraOptions object <optional>
bypassAutoEncryption boolean <optional>

AWSEncryptionKeyOptionsobject

Configuration options for making an AWS encryption key

Properties:
Name Type Argument Description
region string

The AWS region of the KMS

key string

The Amazon Resource Name (ARN) to the AWS customer master key (CMK)

endpoint string <optional>

An alternate host to send KMS requests to. May include port number

AzureEncryptionKeyOptionsobject

Configuration options for making an Azure encryption key

Properties:
Name Type Argument Description
keyName string

Key name

keyVaultEndpoint string

Key vault URL, typically <name>.vault.azure.net

keyVersion string <optional>

Key version

ChangeStreamOptions

Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified.

Properties:
Name Type Argument Default Description
fullDocument string <optional>
'default'

Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.

maxAwaitTimeMS number <optional>

The maximum amount of time for the server to wait on new documents to satisfy a change stream query.

resumeAfter ResumeToken <optional>

Allows you to start a changeStream after a specified event. See ChangeStream documentation.

startAfter ResumeToken <optional>

Similar to resumeAfter, but will allow you to start after an invalidated event. See ChangeStream documentation.

startAtOperationTime OperationTime <optional>

Will start the changeStream after the specified operationTime.

batchSize number <optional>
1000

The number of documents to return per batch. See aggregation documentation.

collation object <optional>

Specify collation settings for operation. See aggregation documentation.

readPreference ReadPreference <optional>

The read preference. Defaults to the read preference of the database or collection. See read preference documentation.

DriverInfoOptionsObject

Configuration options for drivers wrapping the node driver.

Properties:
Name Type Argument Description
name string <optional>

The name of the driver

version string <optional>

The version of the driver

platform string <optional>

Optional platform information

DriverInfoOptionsObject

Configuration options for drivers wrapping the node driver.

Properties:
Name Type Argument Description
name string <optional>

The name of the driver

version string <optional>

The version of the driver

platform string <optional>

Optional platform information

GCPEncryptionKeyOptionsobject

Configuration options for making a GCP encryption key

Properties:
Name Type Argument Description
projectId string

GCP project id

location string

Location name (e.g. "global")

keyRing string

Key ring name

keyName string

Key name

keyVersion string <optional>

Key version

endpoint string <optional>

KMS URL, defaults to https://www.googleapis.com/auth/cloudkms

KMSProvidersobject

Configuration options that are used by specific KMS providers during key generation, encryption, and decryption.

Properties:
Name Type Argument Description
aws object <optional>

Configuration options for using 'aws' as your KMS provider

Properties
Name Type Argument Description
accessKeyId string <optional>

The access key used for the AWS KMS provider

secretAccessKey string <optional>

The secret access key used for the AWS KMS provider

local object <optional>

Configuration options for using 'local' as your KMS provider

Properties
Name Type Argument Description
key Buffer <optional>

The master key used to encrypt/decrypt data keys. A 96-byte long Buffer.

azure object <optional>

Configuration options for using 'azure' as your KMS provider

Properties
Name Type Argument Description
tenantId string <optional>

The tenant ID identifies the organization for the account

clientId string <optional>

The client ID to authenticate a registered application

clientSecret string <optional>

The client secret to authenticate a registered application

identityPlatformEndpoint string <optional>

If present, a host with optional port. E.g. "example.com" or "example.com:443". This is optional, and only needed if customer is using a non-commercial Azure instance (e.g. a government or China account, which use different URLs). Defaults to "login.microsoftonline.com"

gcp object <optional>

Configuration options for using 'gcp' as your KMS provider

Properties
Name Type Argument Description
email string <optional>

The service account email to authenticate

privateKey string | Binary <optional>

A PKCS#8 encrypted key. This can either be a base64 string or a binary representation

endpoint string <optional>

If present, a host with optional port. E.g. "example.com" or "example.com:443". Defaults to "oauth2.googleapis.com"

MongoClientOptionsobject

Properties:
Name Type Argument Description
poolSize number <optional>

(default: 5) The maximum size of the individual server pool

ssl boolean <optional>

(default: false) Enable SSL connection. deprecated use tls variants

sslValidate boolean <optional>

(default: false) Validate mongod server certificate against Certificate Authority

sslCA buffer <optional>

(default: undefined) SSL Certificate store binary buffer deprecated use tls variants

sslCert buffer <optional>

(default: undefined) SSL Certificate binary buffer deprecated use tls variants

sslKey buffer <optional>

(default: undefined) SSL Key file binary buffer deprecated use tls variants

sslPass string <optional>

(default: undefined) SSL Certificate pass phrase deprecated use tls variants

sslCRL buffer <optional>

(default: undefined) SSL Certificate revocation list binary buffer deprecated use tls variants

checkServerIdentity boolean | function <optional>

(default: true) Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. deprecated use tls variants

tls boolean <optional>

(default: false) Enable TLS connections

tlsInsecure boolean <optional>

(default: false) Relax TLS constraints, disabling validation

tlsCAFile string <optional>

A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection

tlsCertificateKeyFile string <optional>

A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated

tlsCertificateKeyFilePassword string <optional>

The password to decrypt the client private key to be used for TLS connections

tlsAllowInvalidCertificates boolean <optional>

Specifies whether or not the driver should error when the server’s TLS certificate is invalid

tlsAllowInvalidHostnames boolean <optional>

Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate

autoReconnect boolean <optional>

(default: true) Enable autoReconnect for single server instances

noDelay boolean <optional>

(default: true) TCP Connection no delay

keepAlive boolean <optional>

(default: true) TCP Connection keep alive enabled

keepAliveInitialDelay number <optional>

(default: 120000) The number of milliseconds to wait before initiating keepAlive on the TCP socket

connectTimeoutMS number <optional>

(default: 10000) How long to wait for a connection to be established before timing out

socketTimeoutMS number <optional>

(default: 0) How long a send or receive on a socket can take before timing out

family number <optional>

Version of IP stack. Can be 4, 6 or null (default). If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure

reconnectTries number <optional>

(default: 30) Server attempt to reconnect #times

reconnectInterval number <optional>

(default: 1000) Server will wait # milliseconds between retries

ha boolean <optional>

(default: true) Control if high availability monitoring runs for Replicaset or Mongos proxies

haInterval number <optional>

(default: 10000) The High availability period for replicaset inquiry

replicaSet string <optional>

(default: undefined) The Replicaset set name

secondaryAcceptableLatencyMS number <optional>

(default: 15) Cutoff latency point in MS for Replicaset member selection

acceptableLatencyMS number <optional>

(default: 15) Cutoff latency point in MS for Mongos proxies selection

connectWithNoPrimary boolean <optional>

(default: false) Sets if the driver should connect even if no primary is available

authSource string <optional>

(default: undefined) Define the database to authenticate against

w number | string <optional>

Deprecated The write concern. Use writeConcern instead.

wtimeout number <optional>

Deprecated The write concern timeout. Use writeConcern instead.

j boolean <optional>

(default: false) Deprecated Specify a journal write concern. Use writeConcern instead.

fsync boolean <optional>

(default: false) Deprecated Specify a file sync write concern. Use writeConcern instead.

writeConcern object | WriteConcern <optional>

Specify write concern settings.

forceServerObjectId boolean <optional>

(default: false) Force server to assign _id values instead of driver

serializeFunctions boolean <optional>

(default: false) Serialize functions on any object

ignoreUndefined Boolean <optional>

(default: false) Specify if the BSON serializer should ignore undefined fields

raw boolean <optional>

(default: false) Return document results as raw BSON buffers

bufferMaxEntries number <optional>

(default: -1) Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited

readPreference ReadPreference | string <optional>

The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)

pkFactory object <optional>

A primary key factory object for generation of custom _id keys

promiseLibrary object <optional>

A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible

readConcern object <optional>

Specify a read concern for the collection (only MongoDB 3.2 or higher supported)

Properties
Name Type Argument Description
level ReadConcernLevel <optional>

(default: {Level: 'local'}) Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)

maxStalenessSeconds number <optional>

(default: undefined) The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)

loggerLevel string <optional>

(default: undefined) The logging level (error/warn/info/debug)

logger object <optional>

(default: undefined) Custom logger object

promoteValues boolean <optional>

(default: true) Promotes BSON values to native types where possible, set to false to only receive wrapper types

promoteBuffers boolean <optional>

(default: false) Promotes Binary BSON values to native Node Buffers

promoteLongs boolean <optional>

(default: true) Promotes long values to number if they fit inside the 53 bits resolution

domainsEnabled boolean <optional>

(default: false) Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit

validateOptions object <optional>

(default: false) Validate MongoClient passed in options for correctness

appname string <optional>

(default: undefined) The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections

options.auth.user string <optional>

(default: undefined) The username for auth

options.auth.password string <optional>

(default: undefined) The password for auth

authMechanism string <optional>

An authentication mechanism to use for connection authentication, see the authMechanism reference for supported options.

compression object <optional>

Type of compression to use: snappy or zlib

readPreferenceTags array <optional>

Read preference tags

numberOfRetries number <optional>

(default: 5) The number of retries for a tailable cursor

auto_reconnect boolean <optional>

(default: true) Enable auto reconnecting for single server instances

monitorCommands boolean <optional>

(default: false) Enable command monitoring for this client

minSize number <optional>

If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections

useNewUrlParser boolean <optional>

(default: true) Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser.

useUnifiedTopology boolean <optional>

Enables the new unified topology layer

localThresholdMS number <optional>

(default: 15) Only applies to the unified topology The size of the latency window for selecting among multiple suitable servers

serverSelectionTimeoutMS number <optional>

(default: 30000) Only applies to the unified topology How long to block for server selection before throwing an error

heartbeatFrequencyMS number <optional>

(default: 10000) Only applies to the unified topology The frequency with which topology updates are scheduled

maxPoolSize number <optional>

(default: 10) Only applies to the unified topology The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections.

minPoolSize number <optional>

(default: 0) Only applies to the unified topology The minimum number of connections that MUST exist at any moment in a single connection pool.

maxIdleTimeMS number <optional>

Only applies to the unified topology The maximum amount of time a connection should remain idle in the connection pool before being marked idle. The default is infinity.

waitQueueTimeoutMS number <optional>

(default: 0) Only applies to the unified topology The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit.

autoEncryption AutoEncryptionOptions <optional>

Optionally enable client side auto encryption.

Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error
(see libmongocrypt: Auto Encryption Allow-List). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts.

Automatic encryption requires the authenticated user to have the listCollections privilege action.

If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true:

  • AutoEncryptionOptions.keyVaultClient is not passed.
  • AutoEncryptionOptions.bypassAutomaticEncryption is false.
    If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted.
driverInfo DriverInfoOptions <optional>

Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver

directConnection boolean <optional>

(default: false) Enable directConnection

callback function <optional>

The command result callback

OperationTime

Represents a specific point in time on a server. Can be retrieved by using Db#command

See:

ReadConcernObject

The MongoDB ReadConcern, which allows for control of the consistency and isolation properties
of the data read from replica sets and replica set shards.

Properties:
Name Type Description
level 'local' | 'available' | 'majority' | 'linearizable' | 'snapshot'

The readConcern Level

See:

ReadConcernLevel'local' 'available' 'majority' 'linearizable' 'snapshot'

A string specifying the level of a ReadConcern

See:

ResumeToken

Represents the logical starting point for a new or resuming ChangeStream on the server.

See:

SessionIdObject

A BSON document reflecting the lsid of a ClientSession

SessionOptionsObject

Options to pass when creating a Client Session

Properties:
Name Type Argument Default Description
causalConsistency boolean <optional>
true

Whether causal consistency should be enabled on this session

defaultTransactionOptions TransactionOptions <optional>

The default TransactionOptions to use for transactions started on this session.

TransactionOptionsObject

Configuration options for a transaction.

Properties:
Name Type Argument Description
readConcern ReadConcern <optional>

A default read concern for commands in this transaction

writeConcern WriteConcern <optional>

A default writeConcern for commands in this transaction

readPreference ReadPreference <optional>

A default read preference for commands in this transaction

WithTransactionCallback(session){Promise}

A user provided function to be run within a transaction

Name Type Description
session ClientSession

The parent session of the transaction running the operation. This should be passed into each operation within the lambda.

Returns:
resulting Promise of operations run within this transaction

WriteConcernObject

A MongoDB WriteConcern, which describes the level of acknowledgement
requested from MongoDB for write operations.

Properties:
Name Type Argument Default Description
w number | 'majority' | string <optional>
1

requests acknowledgement that the write operation has
propagated to a specified number of mongod hosts

j boolean <optional>
false

requests acknowledgement from MongoDB that the write operation has
been written to the journal

wtimeout number <optional>

a time limit, in milliseconds, for the write concern

See: