22.4.1 • Published 10 months ago

mongodb-connection-model v22.4.1

Weekly downloads
516
License
SSPL
Repository
github
Last release
10 months ago

mongodb-connection-model

MongoDB connection model

The main purpose of the MongoDB connection model is to be a domain model around a MongoDB connection. It encapsulates generating a Connection String URI from a group of attributes and parses URI using the MongoDB Node.JS Driver URI Parser.

Installation

npm install --save mongodb-connection-model

Usage

Building URI

const Connection = require('mongodb-connection-model');
const c = new Connection({ appname: 'My App Name' });

console.log(c.driverUrl)
>>> 'mongodb://localhost:27017/?readPreference=primary&appname=My%20App&ssl=false'

Parsing URI

const Connection = require('mongodb-connection-model');

Connection.from(
  'mongodb://someUsername:testPassword@localhost',
  (error, result) => {
    console.log(result);
    >>> `{
      hosts: [{ host: 'localhost', port: 27017 }],
      hostname: 'localhost',
      port: 27017,
      auth: {
        username: 'someUsername',
        password: 'testPassword',
        db: 'admin'
      },
      isSrvRecord: false,
      authStrategy: 'MONGODB',
      mongodbUsername: 'someUsername',
      mongodbPassword: 'testPassword',
      mongodbDatabaseName: 'admin',
      extraOptions: {},
      connectionType: 'NODE_DRIVER',
      readPreference: 'primary',
      kerberosCanonicalizeHostname: false,
      sslMethod: 'NONE',
      sshTunnel: 'NONE',
      sshTunnelPort: 22
    }`
  }
);

Properties

MongoDB connection model is based on Ampersand.js framework and consist of props and derived props. The props object describes the observable properties that MongoDB connection model gets from the Node.js Driver API.

const с = new Connection();
const props = с.getAttributes({ props: true });

See Also

General Properties

const c = new Connection({ isSrvRecord: true });
PropertyTypeDescriptionDefault
nsStringA valid ns the user can read fromundefined
isSrvRecordBooleanIndicates SRV recordfalse
authObjectAuthentication from driver (username, user, db, password)undefined
hostnameStringHostname of a MongoDB Instance. In case of the replica set the first host and port will be takenlocalhost
portNumberTCP port of a MongoDB Instance27017
hostsArrayContains all hosts and ports for replica set[{ host: 'localhost', port: 27017 }]
extraOptionsObjectExtra options passed to the node driver as part of driverOptions{}
connectionTypeStringThe desired connection type. Possible values: NODE_DRIVER, STITCH_ON_PREM, STITCH_ATLASNODE_DRIVER
authStrategyStringThe desired authentication strategy. Possible values: NONE, MONGODB, X509, KERBEROS, LDAP, SCRAM-SHA-256NONE

Connection string options

const c = new Connection({ appname: 'My App', replicaSet: 'testing' });

General connection string options

PropertyTypeDescriptionDefault
replicaSetStringSpecifies the name of the replica set, if the mongod is a member of a replica setundefined
connectTimeoutMSNumberThe time in milliseconds to attempt a connection before timing outundefined
socketTimeoutMSNumberThe time in milliseconds to attempt a send or receive on a socket before the attempt times outundefined
compressionObjectObject includes compressors and a compression level. The following compressors can be specified: snappy, zlib (Available in MongoDB 3.6 or greater)undefined

Connection Pool Option

PropertyTypeDescriptionDefault
maxPoolSizeNumberThe maximum number of connections in the connection poolundefined
minPoolSizeNumberThe minimum number of connections in the connection poolundefined
maxIdleTimeMSNumberThe maximum number of milliseconds that a connection can remain idle in the pool before being removed and closedundefined
waitQueueMultipleNumberA number that the driver multiples the maxPoolSize value to, to provide the maximum number of threads allowed to wait for a connection to become available from the poolundefined
waitQueueTimeoutMSNumberThe maximum time in milliseconds that a thread can wait for a connection to become availableundefined

Write Concern Options

PropertyTypeDescriptionDefault
wNumber/StringCorresponds to the write concern w Optionundefined
wTimeoutMSNumberCorresponds to the write concern wtimeoutundefined
journalBooleanCorresponds to the write concern j Optionundefined

Read Concern Options

PropertyTypeDescriptionDefault
readConcernLevelStringThe level of isolationundefined

Read Preference Options

PropertyTypeDescriptionDefault
readPreferenceStringSpecifies the read preferences for this connection. Possible values: PRIMARY, PRIMARY_PREFERRED, SECONDARY, SECONDARY_PREFERRED, NEARESTPRIMARY
maxStalenessSecondsNumberSpecifies, in seconds, how stale a secondary can be before the client stops using it for read operationsundefined
readPreferenceTagsObjectDefault read preference tags for the clientundefined

Authentication Options

PropertyTypeDescriptionDefault
authSourceStringSpecify the database name associated with the user’s credentialsundefined
authMechanismStringSpecifies the authentication mechanism that MongoDB will use to authenticate the connection. Possible values: DEFAULT, GSSAPI, MONGODB-X509, PLAIN, SCRAM-SHA-256undefined
authMechanismPropertiesObjectAdditional options provided for authentication (e.g. to enable hostname canonicalization for GSSAPI)undefined
gssapiServiceNameStringSet the Kerberos service name when connecting to Kerberized MongoDB instancesundefined
gssapiServiceRealmStringSet the Realm service nameundefined
gssapiCanonicalizeHostNameBooleanWhether canonicalized hostnameundefined

Server Selection and Discovery Options

PropertyTypeDescriptionDefault
localThresholdMSNumberThe size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instancesundefined
serverSelectionTimeoutMSNumberSpecifies how long (in milliseconds) to block for server selection before throwing an exceptionundefined
serverSelectionTryOnceBooleanInstructs the driver to scan the MongoDB deployment exactly once after server selection fails and then either select a server or raise an errorundefined
heartbeatFrequencyMSNumberControls when the driver checks the state of the MongoDB deploymentundefined

Miscellaneous Configuration

PropertyTypeDescriptionDefault
appnameStringAn application name passed to server as client metadataundefined
retryWritesBooleanEnable retryable writesundefined
uuidRepresentationStringThe legacy representation of UUID. Possible values: standard, csharpLegacy, javaLegacy, pythonLegacyundefined
loadBalancedBooleanWhether or not the server is running in load balanced modeundefined

Stitch attributes

PropertyTypeDescriptionDefault
stitchServiceNameStringStitch service nameundefined
stitchClientAppIdStringStitch сlient app IDundefined
stitchGroupIdStringStitch group IDundefined
stitchBaseUrlStringStitch base Urlundefined

MONGODB authentication

const c = new Connection({
  mongodbUsername: 'arlo',
  mongodbPassword: 'w@of'
});

console.log(c.driverUrl)
>>> 'mongodb://arlo:w%40of@localhost:27017/?slaveOk=true&authSource=admin'

console.log(c.driverOptions)
>>> {
  db: { readPreference: 'nearest' },
  replSet: { }
}
PropertyTypeDescriptionDefault
mongodbUsernameStringMongoDB usernameundefined
mongodbPasswordStringMongoDB passwordundefined
mongodbDatabaseNameStringThe database name associated with the user's credentialsundefined
promoteValuesBooleanWhether BSON values should be promoted to their JS type counterpartsundefined

KERBEROS authentication

const c = new Connection({
  kerberosServiceName: 'mongodb',
  kerberosPrincipal: 'arlo/dog@krb5.mongodb.parts',
  ns: 'toys'
});

console.log(c.driverUrl)
>>> 'mongodb://arlo%252Fdog%2540krb5.mongodb.parts@localhost:27017/toys?authMechanism=GSSAPI'

console.log(c.driverOptions)
>>> {
  db: { readPreference: 'nearest' },
  replSet: { }
}

@note (imlucas): Kerberos on Windows is broken out as it's own state for UX consideration

PropertyTypeDescriptionDefault
kerberosServiceNameStringAny program or computer you access over a networkundefined
kerberosPrincipalStringThe format of a typical Kerberos V5 principal is primary/instance@REALMundefined
kerberosCanonicalizeHostnameBooleanWhether canonicalized kerberos hostnameundefined

See Also

LDAP authentication

const c = new Connection({
  ldapUsername: 'arlo',
  ldapPassword: 'w@of',
  ns: 'toys'
});

console.log(c.driverUrl)
>>> 'mongodb://arlo:w%40of@localhost:27017/toys?slaveOk=true&authMechanism=PLAIN'

console.log(c.driverOptions)
>>> {
  db: { readPreference: 'nearest' },
  replSet: { }
}
PropertyTypeDescriptionDefault
ldapUsernameStringLDAP usernameundefined
ldapPasswordStringLDAP passwordundefined

See Also

X509 authentication

const c = new Connection({
  x509Username: 'CN=client,OU=arlo,O=MongoDB,L=Philadelphia,ST=Pennsylvania,C=US'
});

console.log(c.driverUrl)
>>> 'mongodb://CN%253Dclient%252COU%253Darlo%252CO%253DMongoDB%252CL%253DPhiladelphia%252CST%253DPennsylvania%252CC%253DUS@localhost:27017?slaveOk=true&authMechanism=MONGODB-X509'

console.log(c.driverOptions)
>>> {
  db: { readPreference: 'nearest' },
  replSet: { }
}
PropertyTypeDescriptionDefault
x509UsernameStringThe x.509 certificate derived user name, e.g. CN=user,OU=OrgUnit,O=myOrg,...undefined

See Also

SSL

Note: Not to be confused with authentication=X509

PropertyTypeDescriptionDefault
sslNumber/StringA boolean to enable or disables TLS/SSL for the connectionundefined
sslMethodStringThe desired ssl method. Possible values: NONE, SYSTEMCA, IFAVAILABLE, UNVALIDATED, SERVER, ALLNONE
sslCABuffer/StringArray of valid certificatesundefined
sslCertBuffer/StringThe certificateundefined
sslKeyBuffer/StringThe certificate private keyundefined
sslPassBuffer/StringThe certificate passwordundefined

Description of sslMethod values:

See also

SSH TUNNEL

New in mongodb-connection-model@5.0.0

Because authentication is quite difficult for operators to migrate to, the most common method of securing a MongoDB deployment is to use an SSH tunnel. This allows operators to leverage their existing SSH security infrastructure to also provide secure access to MongoDB. For a standard deployment of MongoDB on AWS, this is almost always to strategy. Because of this, we now support creating SSH tunnels automatically when connecting to MongoDB.

const connect = require('mongodb-connection-model').connect;
const options = {
  hostname: 'localhost',
  port: 27017,
  sshTunnel: 'IDENTITY_FILE',
  sshTunnelHostname: 'ec2-11-111-111-111.compute-1.amazonaws.com',
  sshTunnelUsername: 'ubuntu',
  sshTunnelIdentityFile: ['/Users/albert/.ssh/my-key-aws-pair.pem']
};

connect(options, (connectionError, client) => {
  if (connectionError) {
    return console.log(connectionError);
  }

  client.db('mongodb').collection('fanclub').count((countingError, count) => {
    console.log('counted:', countingError, count);
    client.close();
  });
});

The above provides the same functionality as creating the tunnel using the bash command below and connecting to MongoDB via another terminal. Notice that connection-model uses a random local port each time it creates a tunnel. Using the command line, you'd have to replace <random port> with an actual port number.

ssh -i ~/.ssh/my-key-aws-pair.pem -L <random port>:localhost:27017 ubuntu@ec2-11-111-111-111.compute-1.amazonaws.com
PropertyTypeDescriptionDefault
sshTunnelStringThe desired SSH tunnel strategy. Possible values: NONE, USER_PASSWORD, IDENTITY_FILEundefined
sshTunnelHostnameStringThe hostname of the SSH remote hostundefined
sshTunnelPortPortThe SSH port of the remote host22
sshTunnelBindToLocalPortPortBind the localhost endpoint of the SSH Tunnel to this portundefined
sshTunnelUsernameStringThe optional SSH username for the remote hostundefined
sshTunnelPasswordStringThe optional SSH password for the remote hostundefined
sshTunnelIdentityFileString/ArrayThe optional path to the SSH identity file for the remote hostundefined
sshTunnelPassphraseStringThe optional passphrase for sshTunnelIdentityFileundefined

Description of sshTunnel values:

  • NONE - Do not use SSH tunneling.
  • USER_PASSWORD - The tunnel is created with SSH username and password only.
  • IDENTITY_FILE - The tunnel is created using an identity file.

Derived Properties

Derived properties (also known as computed properties) are properties of the state object that depend on other properties to determine their value.

const c = new Connection();
const derivedProps = c.getAttributes({ derived: true });
Derived PropertyTypeDescriptionDefault
instanceIdStringThe mongoscopelocalhost:27017
driverAuthMechanismStringConverts the value of authStrategy for humans into the authMechanism value for the driverundefined
safeUrlStringThe URL where a password is replaced with starsmongodb://localhost:27017/?readPreference=primary&ssl=false
driverUrlStringUse this URL in order to connect via DataServicemongodb://localhost:27017/?readPreference=primary&ssl=false
driverUrlWithSshStringUse this URL in order to connect via connection model itselfmongodb://localhost:29201/?readPreference=primary&ssl=false
driverOptionsStringThe second argument mongoscope-server passes to mongodb.connect{}

Events

New in mongodb-connection-model@5.0.0

Example: SSH Tunnel

const connect = require('mongodb-connection-model').connect;
const options = {
  hostname: 'localhost',
  port: 27017,
  sshTunnel: 'IDENTITY_FILE',
  sshTunnelHostname: 'ec2-11-111-111-111.compute-1.amazonaws.com',
  sshTunnelUsername: 'ubuntu',
  sshTunnelIdentityFile: ['/Users/albert/.ssh/my-key-aws-pair.pem']
};

connect(options).on('status', (evt) => console.log('status:', evt));

This will log the following events to the console:

>>> status: { message: 'Validate', pending: true }
>>> status: { message: 'Validate', complete: true }
>>> status: { message: 'Load SSL files', pending: true }
>>> status: { message: 'Load SSL files', skipped: true,
  reason: 'The selected SSL mode does not need to load any files.' }
>>> status: { message: 'Create SSH Tunnel', pending: true }
>>> status: { message: 'Create SSH Tunnel', complete: true}
>>> status: { message: 'Connect to MongoDB', pending: true }
>>> status: { message: 'Connect to MongoDB', complete: true }

Example: SSL

const connect = require('mongodb-connection-model').connect;
const options = {
  hostname: 'localhost',
  port: 27017,
  ssl: 'ALL',
  sslCA: '~/.ssl/my-ca.pem',
  sslCert: '~/.ssl/my-server.pem',
  sslKey: '~/.ssl/my-server.pem'
};

connect(options).on('status', (evt) => console.log('status:', evt));

This will log the following events to the console:

>>> status: { message: 'Validate', pending: true }
>>> status: { message: 'Validate', complete: true }
>>> status: { message: 'Load SSL files', pending: true }
>>> status: { message: 'Load SSL files', complete: true}
>>> status: { message: 'Create SSH Tunnel', pending: true }
>>> status: { message: 'Create SSH Tunnel', skipped: true,
  reason: 'The selected SSH Tunnel mode is NONE.'}
>>> status: { message: 'Connect to MongoDB', pending: true }
>>> status: { message: 'Connect to MongoDB', complete: true }
22.4.1

11 months ago

22.4.0

11 months ago

22.3.0

1 year ago

22.2.1

1 year ago

22.2.0

1 year ago

22.2.3

1 year ago

22.2.2

1 year ago

22.1.2

2 years ago

22.1.3

1 year ago

22.1.1

2 years ago

22.0.0

2 years ago

21.18.0

2 years ago

21.19.1

2 years ago

21.19.0

2 years ago

21.16.0

2 years ago

21.17.0

2 years ago

21.15.0

2 years ago

21.12.2

2 years ago

21.13.0

2 years ago

21.14.0

2 years ago

21.10.0

2 years ago

21.11.1

2 years ago

21.11.0

2 years ago

21.12.1

2 years ago

21.12.0

2 years ago

21.9.0

2 years ago

21.8.0

3 years ago

21.7.0

3 years ago

21.6.0

3 years ago

21.5.4

3 years ago

21.5.3

3 years ago

21.5.2

3 years ago

21.4.0

3 years ago

21.5.1

3 years ago

21.5.0

3 years ago

21.3.0

3 years ago

21.1.0

3 years ago

21.2.0

3 years ago

21.0.0

3 years ago

20.2.0

3 years ago

19.2.1

3 years ago

19.2.0

3 years ago

20.0.0

3 years ago

20.1.0

3 years ago

19.1.1

3 years ago

19.1.0

3 years ago

19.0.3

3 years ago

19.0.2

3 years ago

19.0.1

3 years ago

19.0.0

3 years ago

18.1.0

3 years ago

18.0.1

3 years ago

18.0.0

3 years ago

17.3.0

3 years ago

17.2.0

3 years ago

17.1.0

3 years ago

17.0.3

3 years ago

17.0.2

3 years ago

17.0.1

4 years ago

17.0.0

4 years ago

16.1.8

4 years ago

16.1.7

4 years ago

16.1.6

4 years ago

16.1.5

4 years ago

16.1.4

4 years ago

16.1.3

4 years ago

16.1.2

4 years ago

16.1.1

4 years ago

16.1.0

4 years ago

16.0.1

4 years ago

14.6.6

4 years ago

16.0.0

4 years ago

14.6.5

4 years ago

14.6.4

4 years ago

14.6.3

4 years ago

14.6.2

4 years ago

14.6.1

4 years ago

14.6.0

4 years ago

14.5.1

4 years ago

14.4.3

4 years ago

14.5.0

4 years ago

14.4.1

4 years ago

14.4.2

4 years ago

14.4.0

4 years ago

14.3.7

4 years ago

14.3.6

4 years ago

14.3.5

4 years ago

14.3.4

4 years ago

14.3.3

4 years ago

14.3.2

5 years ago

14.3.1

5 years ago

14.3.0

5 years ago

14.2.8

5 years ago

14.2.7

5 years ago

14.2.6

5 years ago

14.2.5

5 years ago

14.2.4

5 years ago

14.2.3

5 years ago

14.2.2

5 years ago

14.2.0

5 years ago

14.1.1

5 years ago

14.1.0

5 years ago

14.0.3

5 years ago

14.0.2

5 years ago

13.1.6

5 years ago

14.0.1

5 years ago

14.0.0

5 years ago

13.1.5

5 years ago

13.1.4

5 years ago

13.1.3

5 years ago

13.1.2

5 years ago

13.1.1

5 years ago

13.1.0

5 years ago

13.0.1

5 years ago

13.0.0

5 years ago

12.5.6

5 years ago

12.5.5

5 years ago

12.5.4

5 years ago

12.5.3

5 years ago

12.5.2

5 years ago

12.5.1

5 years ago

12.5.0

6 years ago

12.4.2

6 years ago

12.4.1

6 years ago

12.4.0

6 years ago

12.3.2

6 years ago

12.3.1

6 years ago

12.3.0

6 years ago

12.2.0

6 years ago

12.1.0

6 years ago

12.0.5

6 years ago

12.0.4

6 years ago

12.0.3

6 years ago

12.0.2

6 years ago

12.0.1

6 years ago

12.0.0

6 years ago

11.0.0

6 years ago

10.7.1

6 years ago

10.7.0

6 years ago

10.6.0

6 years ago

10.5.0

6 years ago

10.4.3

6 years ago

10.4.2

7 years ago

10.4.1

7 years ago

10.4.0

7 years ago

10.3.0

7 years ago

10.2.0

7 years ago

10.1.3

7 years ago

10.1.2

7 years ago

10.1.1

7 years ago

10.1.0

7 years ago

10.0.2

7 years ago

10.0.1

7 years ago

10.0.0

7 years ago

9.2.0

7 years ago

9.1.0

7 years ago

9.0.0

7 years ago

9.0.0-beta.0

7 years ago

8.0.1

7 years ago

8.0.0

7 years ago

8.0.0-beta.1

7 years ago

8.0.0-beta.0

7 years ago

7.0.0

7 years ago

6.5.2

7 years ago

6.5.1

7 years ago

6.5.0

7 years ago

6.4.3

7 years ago

6.4.2

7 years ago

6.4.1

7 years ago

6.4.0

7 years ago

6.3.5

7 years ago

6.3.4

7 years ago

6.3.3

7 years ago

6.3.2

7 years ago

6.3.1

8 years ago

6.3.0

8 years ago

6.2.0

8 years ago

6.1.0

8 years ago

6.0.0

8 years ago

5.1.0

8 years ago

5.0.3

8 years ago

5.0.2

8 years ago

5.0.1

8 years ago

5.0.0

8 years ago

4.3.0

8 years ago

4.2.0

8 years ago

4.1.0

8 years ago

4.0.4

8 years ago

4.0.3

8 years ago

4.0.2

8 years ago

4.0.1

8 years ago

4.0.0

8 years ago

3.0.10

8 years ago

3.0.9

8 years ago

3.0.8

8 years ago

3.0.7

8 years ago

3.0.6

9 years ago

3.0.5

9 years ago

3.0.4

9 years ago

3.0.3

9 years ago

3.0.2

9 years ago

3.0.1

9 years ago

3.0.0

9 years ago

2.0.1

9 years ago

2.0.0

9 years ago

1.0.2

9 years ago

1.0.1

9 years ago

1.0.0

9 years ago

0.0.3

9 years ago

0.0.2

9 years ago

0.0.1

9 years ago