npm

Ready to take your JavaScript development to the next level? Meet npm Enterprise - the ultimate in enterprise JavaScript.Learn more »

mongodb-connection-model

14.2.6 • Public • Published

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' });
 
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',
      name: 'Local',
      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 });
Property Type Description Default
name String User specified name My MongoDB
ns String A valid ns the user can read from undefined
isSrvRecord Boolean Indicates SRV record false
auth Object Authentication from driver (username, user, db, password) undefined
hostname String Hostname of a MongoDB Instance. In case of the replica set the first host and port will be taken localhost
port Number TCP port of a MongoDB Instance 27017
hosts Array Contains all hosts and ports for replica set [{ host: 'localhost', port: 27017 }]
extraOptions Object Extra options passed to the node driver as part of driverOptions {}
connectionType String The desired connection type. Possible values: NODE_DRIVER, STITCH_ON_PREM, STITCH_ATLAS NODE_DRIVER
authStrategy String The desired authentication strategy. Possible values: NONE, MONGODB, X509, KERBEROS, LDAP, SCRAM-SHA-256 NONE

Connection string options

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

General connection string options

Property Type Description Default
replicaSet String Specifies the name of the replica set, if the mongod is a member of a replica set undefined
connectTimeoutMS Number The time in milliseconds to attempt a connection before timing out undefined
socketTimeoutMS Number The time in milliseconds to attempt a send or receive on a socket before the attempt times out undefined
compression Object Object 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

Property Type Description Default
maxPoolSize Number The maximum number of connections in the connection pool undefined
minPoolSize Number The minimum number of connections in the connection pool undefined
maxIdleTimeMS Number The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed undefined
waitQueueMultiple Number A 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 pool undefined
waitQueueTimeoutMS Number The maximum time in milliseconds that a thread can wait for a connection to become available undefined

Write Concern Options

Property Type Description Default
w Number/String Corresponds to the write concern w Option undefined
wTimeoutMS Number Corresponds to the write concern wtimeout undefined
journal Boolean Corresponds to the write concern j Option undefined

Read Concern Options

Property Type Description Default
readConcernLevel String The level of isolation undefined

Read Preference Options

Property Type Description Default
readPreference String Specifies the read preferences for this connection. Possible values: PRIMARY, PRIMARY_PREFERRED, SECONDARY, SECONDARY_PREFERRED, NEAREST PRIMARY
maxStalenessSeconds Number Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations undefined
readPreferenceTags Object Default read preference tags for the client undefined

Authentication Options

Property Type Description Default
authSource String Specify the database name associated with the user’s credentials undefined
authMechanism String Specifies the authentication mechanism that MongoDB will use to authenticate the connection. Possible values: DEFAULT, GSSAPI, MONGODB-X509, PLAIN, SCRAM-SHA-256 undefined
authMechanismProperties Object Additional options provided for authentication (e.g. to enable hostname canonicalization for GSSAPI) undefined
gssapiServiceName String Set the Kerberos service name when connecting to Kerberized MongoDB instances undefined
gssapiServiceRealm String Set the Realm service name undefined
gssapiCanonicalizeHostName Boolean Whether canonicalized hostname undefined

Server Selection and Discovery Options

Property Type Description Default
localThresholdMS Number The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances undefined
serverSelectionTimeoutMS Number Specifies how long (in milliseconds) to block for server selection before throwing an exception undefined
serverSelectionTryOnce Boolean Instructs the driver to scan the MongoDB deployment exactly once after server selection fails and then either select a server or raise an error undefined
heartbeatFrequencyMS Number Controls when the driver checks the state of the MongoDB deployment undefined

Miscellaneous Configuration

Property Type Description Default
appname String An application name passed to server as client metadata undefined
retryWrites Boolean Enable retryable writes undefined
uuidRepresentation String The legacy representation of UUID. Possible values: standard, csharpLegacy, javaLegacy, pythonLegacy undefined

Stitch attributes

Property Type Description Default
stitchServiceName String Stitch service name undefined
stitchClientAppId String Stitch сlient app ID undefined
stitchGroupId String Stitch group ID undefined
stitchBaseUrl String Stitch base Url undefined

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: { connectWithNoPrimary: true }
}
Property Type Description Default
mongodbUsername String MongoDB username undefined
mongodbPassword String MongoDB password undefined
mongodbDatabaseName String The database name associated with the user's credentials undefined
promoteValues Boolean Whether BSON values should be promoted to their JS type counterparts undefined

KERBEROS authentication

const c = new Connection({
  kerberosServiceName: 'mongodb',
  kerberosPrincipal: 'arlo/dog@krb5.mongodb.parts',
  kerberosPassword: 'w@@f',
  ns: 'toys'
});
 
console.log(c.driverUrl)
>>> 'mongodb://arlo%252Fdog%2540krb5.mongodb.parts:w%40%40f@localhost:27017/toys?slaveOk=true&gssapiServiceName=mongodb&authMechanism=GSSAPI'
 
console.log(c.driverOptions)
>>> {
  db: { readPreference: 'nearest' },
  replSet: { connectWithNoPrimary: true }
}

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

Property Type Description Default
kerberosServiceName String Any program or computer you access over a network undefined
kerberosPrincipal String The format of a typical Kerberos V5 principal is primary/instance@REALM undefined
kerberosPassword String You can optionally include a password for a kerberos connection undefined
kerberosCanonicalizeHostname Boolean Whether canonicalized kerberos hostname undefined

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: { connectWithNoPrimary: true }
}
Property Type Description Default
ldapUsername String LDAP username undefined
ldapPassword String LDAP password undefined

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: { connectWithNoPrimary: true }
}
Property Type Description Default
x509Username String The 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

Property Type Description Default
ssl Number/String A boolean to enable or disables TLS/SSL for the connection undefined
sslMethod String The desired ssl method. Possible values: NONE, SYSTEMCA, IFAVAILABLE, UNVALIDATED, SERVER, ALL NONE
sslCA Buffer/String Array of valid certificates undefined
sslCert Buffer/String The certificate undefined
sslKey Buffer/String The certificate private key undefined
sslPass Buffer/String The certificate password undefined

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
Property Type Description Default
sshTunnel String The desired SSH tunnel strategy. Possible values: NONE, USER_PASSWORD, IDENTITY_FILE undefined
sshTunnelHostname String The hostname of the SSH remote host undefined
sshTunnelPort Port The SSH port of the remote host 22
sshTunnelBindToLocalPort Port Bind the localhost endpoint of the SSH Tunnel to this port undefined
sshTunnelUsername String The optional SSH username for the remote host undefined
sshTunnelPassword String The optional SSH password for the remote host undefined
sshTunnelIdentityFile String/Array The optional path to the SSH identity file for the remote host undefined
sshTunnelPassphrase String The optional passphrase for sshTunnelIdentityFile undefined

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 Property Type Description Default
instanceId String The mongoscope localhost:27017
driverAuthMechanism String Converts the value of authStrategy for humans into the authMechanism value for the driver undefined
driverUrl String The first argument mongoscope-server passes to mongodb.connect mongodb://localhost:27017/?slaveOk=true
driverOptions String The 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 }

License

Apache 2.0

Keywords

install

npm i mongodb-connection-model

Downloadsweekly downloads

443

version

14.2.6

license

Apache-2.0

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
Report a vulnerability