Skip to content

Commit 8b74840

Browse files
author
Chris Cho
authored
DOCSP-8058 NodeJS Connection Guide (#23)
* DOCSP-8058 nodejs connection guide
1 parent 497fedf commit 8b74840

File tree

6 files changed

+627
-0
lines changed

6 files changed

+627
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ build/
66
*.bak
77
giza.log
88
.vscode*
9+
*.swp

source/connection-settings.txt

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
===================
2+
Connection Settings
3+
===================
4+
5+
This section describes common MongoDB client connection settings for the
6+
Node.js driver. These settings provide additional control over the negotiation
7+
of the connection and the behavior of the client, once a connection is
8+
established.
9+
10+
The connection settings are passed as an optional parameter to the
11+
``MongoClient`` as shown in the code sample below:
12+
13+
.. code-block:: js
14+
15+
const { MongoClient } = require("mongodb");
16+
17+
// Connection URI
18+
const uri = `mongodb+srv://<username>:<password>@<clusterUrl>`;
19+
20+
// Replace this with your constructor options
21+
const opts = {
22+
loggerLevel: "info",
23+
useUnifiedTopology: true,
24+
};
25+
26+
// Create a new MongoClient
27+
const client = new MongoClient(uri, opts);
28+
29+
async function run() {
30+
try {
31+
// Connect the client to the server
32+
await client.connect();
33+
34+
// Establish and verify connection
35+
await client.db("admin").command({ ping: 1 });
36+
console.log("Connected successfully to server");
37+
} finally {
38+
// Ensures that the client will close when you finish/error
39+
await client.close();
40+
}
41+
}
42+
run().catch(console.dir);
43+
44+
The following table describes several common connection options that can be
45+
passed to the ``MongoClient`` constructor.
46+
47+
.. list-table::
48+
:header-rows: 1
49+
50+
* - Option Name
51+
- Type
52+
- Default Value
53+
- Description
54+
* - **useUnifiedTopology**
55+
- boolean
56+
- **false**
57+
- Specifies whether to opt into the new Server Discovery and Monitoring
58+
(SDAM) engine. The next major driver release removes the old engine and
59+
deprecates this option.
60+
* - **validateOptions**
61+
- boolean
62+
- **false**
63+
- Specifies whether to error when instantiating the client the constructor
64+
is passed an unknown option. If ``false``, the driver produces warnings
65+
only.
66+
* - **poolSize**
67+
- integer
68+
- **5**
69+
- Specifies the maximum size of the individual server connection pool.
70+
* - **minSize**
71+
- integer
72+
- **0**
73+
- Specifies the minimum size of connections to maintain in the individual
74+
server pool.
75+
* - **tlsInsecure**
76+
- boolean
77+
- **false**
78+
- Specifies whether to skip validation of the server certificate with the
79+
Certificate Authority.
80+
* - **family**
81+
- number
82+
- **null**
83+
- Specifies the version of the IP stack. Possible values include: **4**,
84+
**6**, **0**, or **null**. The **0** and **null** settings attempt to
85+
connect with IPv6 and fall back to IPv4 upon failure.
86+
* - **tlsCAFile**
87+
- string
88+
- **null**
89+
- Specifies the path to a file containing one or more certificate
90+
authorities to trust when establishing a TLS connection.
91+
* - **tlsCertificateFile**
92+
- string
93+
- **null**
94+
- Specifies the path to the client certificate file or the client private
95+
key file. If both are required, the two files should be concatenated.
96+
* - **tlsCertificateKeyFilePassword**
97+
- string
98+
- **null**
99+
- Specifies the password to decrypt client private key used for TLS
100+
connections.
101+
* - **noDelay**
102+
- boolean
103+
- **true**
104+
- Specifies whether to use the TCP socket no delay option. For more
105+
information, see the documentation for `Node.js socket.setNoDelay
106+
<https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_setnodelay_nodelay>`_.
107+
* - **keepAlive**
108+
- boolean
109+
- **true**
110+
- Specifies whether ``keepAlive`` is enabled on the TCP socket. For more
111+
information, see the documentation for `Node.js socket.setKeepAlive
112+
<https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_setkeepalive_enable_initialdelay>`_.
113+
* - **keepAliveInitialDelay**
114+
- integer
115+
- **30000**
116+
- Specifies the number of milliseconds to wait before initiating
117+
``keepAlive`` on the TCP socket. For more information, see the
118+
documentation for `Node.js socket.setKeepAlive
119+
<https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_setkeepalive_enable_initialdelay>`_.
120+
* - **connectTimeoutMS**
121+
- integer
122+
- **30000**
123+
- Specifies the number of milliseconds to wait before timeout on a TCP
124+
connection.
125+
* - **socketTimeoutMS**
126+
- integer
127+
- **360000**
128+
- Specifies the number of milliseconds to wait before timeout on a TCP
129+
socket.
130+
* - **w**
131+
- string or integer
132+
- **null**
133+
- Specifies the write concern. For more information on values, see the
134+
server documentation on the
135+
:manual:`w Option </reference/write-concern/#w-option>`.
136+
* - **forceServerObjectId**
137+
- boolean
138+
- **false**
139+
- Specifies whether to force the server to assign ``_id`` values to
140+
documents instead of the driver.
141+
* - **serializeFunctions**
142+
- boolean
143+
- **false**
144+
- Specifies whether to serialize functions on any object passed to the
145+
server.
146+
* - **ignoreUndefined**
147+
- boolean
148+
- **false**
149+
- Specifies whether the BSON serializer should ignore undefined fields.
150+
* - **raw**
151+
- boolean
152+
- **false**
153+
- Specifies whether to return document results as raw BSON buffers.
154+
* - **promoteLongs**
155+
- boolean
156+
- **true**
157+
- Specifies whether to convert ``Long`` values to a number if they fit
158+
inside 53 bits of resolution.
159+
* - **promoteBuffers**
160+
- boolean
161+
- **false**
162+
- Specifies whether to promote Binary BSON values to native Node.js
163+
``Buffer`` type data.
164+
* - **promoteValues**
165+
- boolean
166+
- **true**
167+
- Specifies whether to promote BSON values to Node.js native types when
168+
possible. When set to false, BSON values are presented as wrapper types.
169+
* - **pkFactory**
170+
- object
171+
- **null**
172+
- Specifies a primary key factory object that generates custom ``_id``
173+
keys.
174+
* - **promiseLibrary**
175+
- object
176+
- **null**
177+
- Specifies the Promise library class the application uses (e.g. Bluebird).
178+
This library must be compatible with ES6.
179+
* - **loggerLevel**
180+
- string
181+
- **null**
182+
- Specifies the logger level used by the driver. Valid choices are:
183+
``error``, ``warn``, ``info``, and ``debug``.
184+
* - **logger**
185+
- object
186+
- **null**
187+
- Specifies a custom logger to be used by the client.
188+
189+
For a complete list of options, see the :node-api:`MongoClient
190+
<MongoClient.html>` API reference page.

source/getting-started.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,7 @@ Getting Started
99

1010
.. toctree::
1111
:caption: Examples
12+
:maxdepth: 1
1213

14+
/getting-started/authentication
1315
/getting-started/crud-guide
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
====================================
2+
Enterprise Authentication Mechanisms
3+
====================================
4+
5+
In this section, you can find sample code for connection to MongoDB with each
6+
authentication mechanism available in the MongoDB Enterprise Edition:
7+
``Kerberos (GSSAPI/SSPI)`` and ``LDAP (PLAIN)``.
8+
9+
``Kerberos (GSSAPI/SSPI)``
10+
--------------------------
11+
12+
.. note::
13+
The Node.js driver supports Kerberos on UNIX using the MIT Kerberos library
14+
and on Windows using the SSPI API.
15+
16+
The ``GSSAPI`` authentication mechanism uses your user principal to
17+
authenticate to a Kerberos service.
18+
19+
You can specify this authentication mechanism by setting the following
20+
parameters of the
21+
:manual:`URI ConnectionString </manual/reference/connection-string/>`:
22+
23+
- Set the ``authMechanism`` parameter to ``GSSAPI``
24+
- Set the ``gssapiServiceName`` if using a value other than ``mongodb``
25+
- Specify a ``SERVICE_REALM`` value in the ``authMechanismProperties``
26+
parameter if a custom service realm is required.
27+
28+
The following code sample authenticates to Kerberos for UNIX using ``GSSAPI``.
29+
30+
.. code-block:: js
31+
32+
const { MongoClient } = require("mongodb");
33+
34+
// specify the placeholder values for your environment in the following lines
35+
const clusterUrl = "<MongoDB cluster URL>";
36+
const principal = encodeURIComponent("<Kerberos principal and realm>");
37+
const serviceRealm = "<Kerberos service realm>";
38+
const authMechanismProperties = `SERVICE_REALM:${serviceRealm}`;
39+
40+
const authMechanism = "GSSAPI";
41+
42+
// Connection URI
43+
const uri = `mongodb+srv://${principal}@${clusterUrl}/?authMechanism=${authMechanism}&authMechanismProperties=${authMechanismProperties}`;
44+
45+
const client = new MongoClient(uri);
46+
47+
// Function to connect to the server
48+
async function run() {
49+
try {
50+
// Connect the client to the server
51+
await client.connect();
52+
53+
// Establish and verify connection
54+
await client.db("admin").command({ ping: 1 });
55+
console.log("Connected successfully to server");
56+
} finally {
57+
// Ensures that the client will close when you finish/error
58+
await client.close();
59+
}
60+
}
61+
run().catch(console.dir);
62+
63+
.. note::
64+
The method refers to the ``GSSAPI`` authentication mechanism instead
65+
of ``Kerberos`` because the driver authenticates via
66+
`GSSAPI RFC-4652 <https://tools.ietf.org/html/rfc4752>`_ the SASL
67+
mechanism.
68+
69+
``LDAP (PLAIN)``
70+
----------------
71+
72+
The ``PLAIN`` authentication mechanism uses your username and password to
73+
authenticate to a Lightweight Directory Access Protocol (LDAP) server.
74+
75+
You can specify this authentication mechanism by setting the ``authMechanism``
76+
parameter to ``PLAIN`` and including your LDAP username and password in the
77+
:manual:`URI ConnectionString </reference/connection-string/>` as shown
78+
in the following sample code.
79+
80+
.. code-block:: js
81+
82+
const { MongoClient } = require("mongodb");
83+
84+
// specify the placeholder values for your environment in the following lines
85+
const clusterUrl = "<MongoDB cluster URL>";
86+
const ldapUsername = "<LDAP username>";
87+
const ldapPassword = "<LDAP password>";
88+
const authMechanism = "PLAIN";
89+
90+
// Connection URI
91+
const uri = `mongodb+srv://${ldapUsername}:${ldapPassword}@${clusterUrl}/?authMechanism=${authMechanism}`;
92+
93+
const client = new MongoClient(uri);
94+
95+
// Function to connect to the server
96+
async function run() {
97+
try {
98+
// Connect the client to the server
99+
await client.connect();
100+
101+
// Establish and verify connection
102+
await client.db("admin").command({ ping: 1 });
103+
console.log("Connected successfully to server");
104+
} finally {
105+
// Ensures that the client will close when you finish/error
106+
await client.close();
107+
}
108+
}
109+
run().catch(console.dir);
110+
111+
.. note::
112+
The authentication mechanism is named ``PLAIN`` instead of ``LDAP`` since it
113+
authenticates using the `PLAIN Simple Authentication and Security Layer
114+
(SASL) defined in RFC-4616 <https://tools.ietf.org/html/rfc4616>`_.

0 commit comments

Comments
 (0)