@@ -7,193 +7,200 @@ Quick Start
7
7
.. contents:: On this page
8
8
:local:
9
9
:backlinks: none
10
- :depth: 1
10
+ :depth: 2
11
11
:class: singlecol
12
12
13
- This guide shows you how to create an application that uses the Node.js
14
- driver to connect to a MongoDB Atlas cluster.
13
+ This guide shows you how to create an application that uses the
14
+ **Node.js driver** to connect to a **MongoDB Atlas cluster**. If you
15
+ prefer to connect to MongoDB using a different driver or programming
16
+ language, see our :driver:`list of official drivers <>`.
15
17
16
- Check for Node and NPM
17
- ----------------------
18
+ The Node.js driver is an interface through which you can connect to and
19
+ communicate with MongoDB instances.
18
20
19
- Ensure your system has Node version 8 or later and NPM (Node Package
20
- Manager) installed. Run the following commands to check that you meet
21
- these requirements:
21
+ MongoDB Atlas is a fully-managed cloud database service that hosts your data
22
+ on MongoDB instances. We show you how to get started with your own free (no
23
+ credit card required) instance in this guide.
22
24
23
- First, check the version of Node:
25
+ Follow the steps below to connect your Node.js application with a MongoDB
26
+ instance.
24
27
25
- .. code-block:: sh
28
+ Set up Your Project
29
+ -------------------
26
30
27
- node -v
31
+ Install Node and NPM
32
+ ~~~~~~~~~~~~~~~~~~~~
28
33
29
- You should see output similar to the following:
30
-
31
- .. code-block:: sh
32
-
33
- v12.14.1
34
-
35
- Next, check the version of NPM:
36
-
37
- .. code-block:: sh
38
-
39
- npm -v
40
-
41
- You should see output similar to the following:
42
-
43
- .. code-block:: sh
44
-
45
- 6.13.4
46
-
47
- If you do not see any output or encounter an error, you will need to
48
- install Node and NPM. Visit `nodejs.org <https://nodejs.org>`_ for
49
- installation instructions.
34
+ Ensure your system has Node.js version 8 or later and NPM (Node Package
35
+ Manager) version 5 or later installed. For more information on how to check
36
+ your version of Node and NPM and installation instructions for your
37
+ system, see `downloading and installing Node.js and npm
38
+ <https://docs.npmjs.com/downloading-and-installing-node-js-and-npm>`_.
50
39
51
40
Initialize the Project
52
- ----------------------
41
+ ~~~~~~~~~~~~~~~~~~~~~~
53
42
54
- Now that our system meets the Node driver's requirements, we can
43
+ After you verify that you installed the required versions of Node and NPM,
55
44
create a new project.
56
45
57
- First, create a directory for your project:
46
+ First, create a directory for your project in your command line interface :
58
47
59
- .. code-block:: sh
48
+ .. code-block:: none
60
49
61
- mkdir node_quickstart
50
+ mkdir node_quickstart
62
51
63
52
Then, navigate into that directory so you can work directly with your
64
53
project's files:
65
54
66
- .. code-block:: sh
55
+ .. code-block:: none
67
56
68
57
cd node_quickstart
69
58
70
- Finally, initialize npm:
59
+ Next, set up NPM for your project by running the following command.
60
+ This command creates a file called ``package.json``:
71
61
72
- .. code-block:: sh
62
+ .. code-block:: none
73
63
74
64
npm init -y
75
65
76
66
.. admonition:: Why the -y?
77
67
:class: note
78
68
79
- Specifying ``-y`` tells NPM to use default values. You can omit the
80
- ``-y`` flag to proceed through an interactive selection process for
81
- common project settings.
69
+ If you specify the ``-y`` option in the command, NPM automatically
70
+ accepts the default values for the command. Omit the ``-y`` flag to
71
+ interactively select your project settings.
82
72
83
73
Add MongoDB as a Dependency
84
- ---------------------------
85
-
86
- Next, add the Node MongoDB driver as a project dependency. Use the
87
- ``--save`` flag to save the dependency to the ``package.json`` file that
88
- was automatically generated in the previous step.
89
-
90
- .. code-block:: sh
91
-
92
- npm install --save mongodb
74
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
93
75
94
- NPM downloads the dependencies required for installation and saves them
95
- into a directory called ``node_modules`` in your project directory.
76
+ Next, add the official Node.js MongoDB driver to your project dependencies.
77
+ Use the following command to instruct NPM to download and install the
78
+ ``mongodb`` package.
96
79
97
- Create a Free Tier Cluster in Atlas
98
- -----------------------------------
80
+ .. code-block:: none
99
81
100
- You can easily get started with MongoDB with :atlas:`MongoDB Atlas
101
- <tutorial/create-atlas-account>`, which offers instances of MongoDB
102
- hosted in the cloud. Atlas doesn't require a credit card to
103
- sign up, and offers free-tier deployments that are free for life. Follow
104
- along with our :atlas:`steps to create and set up a free-tier cluster
105
- <tutorial/create-atlas-account/>`, then :atlas:`load sample data
106
- <sample-data/load-sample-data/>` to run the examples in this guide.
82
+ npm install mongodb
107
83
108
- Store Configuration Separately
109
- ------------------------------
84
+ This command downloads ``mongodb`` package and dependencies required for its
85
+ installation and saves them into a directory called ``node_modules`` in
86
+ your project directory, and records the dependency information in the
87
+ ``package.json`` file you generated in the previous step.
110
88
111
- You can store your application configuration separately for security
112
- and convenience. We use the `dotenv
113
- <https://www.npmjs.com/package/dotenv>`_ NPM module to store our
114
- configuration data in a separate local file called ``.env``. If you are
115
- using git source control, add the ``.env`` file to your ``.gitignore``
116
- entries to prevent accidentally sharing contents such as database
117
- credentials.
89
+ At this point, you should have appropriate versions of Node.js and NPM
90
+ installed as well as a project directory that contains the dependencies you
91
+ need to use the Node.js MongoDB driver.
118
92
119
- First, add ``dotenv`` to your project:
93
+ Create a MongoDB Cluster
94
+ ------------------------
120
95
121
- .. code-block:: sh
96
+ Set up a Free Tier Cluster in Atlas
97
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
122
98
123
- npm install --save dotenv
99
+ After installing the Node MongoDB driver, create a MongoDB instance to store
100
+ and manage your data. Complete the
101
+ :atlas:`Get Started with Atlas <getting-started>` guide to set up a new
102
+ Atlas account, free tier cluster (MongoDB instance), load datasets, and
103
+ interact with the data.
124
104
125
- Next, create the ``.env`` file and add a variable called
126
- ``MONGODB_URI``:
105
+ After completing the steps in the Atlas guide, you should have a new MongoDB
106
+ cluster deployed in Atlas, a new database user, and sample datasets loaded
107
+ into your cluster.
127
108
128
- .. code-block:: sh
129
-
130
- touch .env
131
- echo "MONGODB_URI=<connection_uri>" >> .env
109
+ Connect to your Cluster
110
+ -----------------------
132
111
133
- Add your Atlas Connection String
134
- --------------------------------
112
+ In this step, we create and run an application that uses the Node.js MongoDB
113
+ driver to connect to your instance of MongoDB and run a query on the sample
114
+ data.
135
115
136
- Open your newly created ``.env`` file. If you are unable to locate this
137
- file in your project directory, you may need to set your system to
138
- display hidden files. Once your ``.env`` is open, replace
139
- ``<connection_uri>`` with your connection string from Atlas. Ensure you
140
- update ``<username>`` and ``<password>`` in your connection string .
116
+ We pass instructions to the driver on where and how to connect to your
117
+ MongoDB instance in a string called the *connection string*. This string
118
+ includes information on the hostname or IP address and port of your
119
+ instance, authentication mechanism, user credentials when applicable, and
120
+ other connection options .
141
121
142
- Connect to your Cluster
143
- -----------------------
122
+ To retrieve your connection string for the instance and user you created in
123
+ the previous step, log into your Atlas account and navigate to the
124
+ **Clusters** section and click the **Connect** button for the cluster that you
125
+ want to connect to as shown below.
144
126
145
- For the final step, we'll write some code that tests your environment's
146
- connection to your instance of MongoDB.
127
+ .. figure:: /includes/figures/atlas_connection_select_cluster.png
147
128
148
- Create a file in your project directory called ``index.js``:
129
+ Proceed to the **Connect Your Application** step and select the Node.js
130
+ driver. Select the "Connection String Only" tab and click the **Copy**
131
+ button to copy the *connection string* to your clipboard as shown below.
149
132
150
- .. code-block :: sh
133
+ .. figure :: /includes/figures/atlas_connection_copy_string.png
151
134
152
- touch index.js
135
+ Save your connection string to a safe location that you can access in the
136
+ next step.
153
137
154
- Open this file and paste in the following code:
138
+ Next, create a file to contain your application called ``index.js`` in your
139
+ ``node_quickstart`` directory. Add the following code, replacing the ``uri``
140
+ variable with your connection string. Make sure to replace the "<password>"
141
+ section of the connection string with the password you created for your user
142
+ that has **atlasAdmin** permissions.
155
143
156
144
.. code-block:: js
157
145
158
146
const { MongoClient } = require("mongodb");
159
- require("dotenv").config();
160
147
161
- if (!process.env.MONGODB_URI) {
162
- throw Error("MONGODB_URI not defined in a .env file. Did you set it up?");
163
- }
148
+ // Replace the uri string with your MongoDB deployment's connection string.
149
+ const uri =
150
+ "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&w=majority&useUnifiedTopology=true";
164
151
165
- const client = new MongoClient(process.env.MONGODB_URI, {
166
- useUnifiedTopology: true
167
- });
152
+ const client = new MongoClient(uri);
168
153
169
154
async function run() {
170
155
try {
171
- // Connect the client to the server
172
156
await client.connect();
173
- // Establish and verify connection
174
- await client.db("admin").command({ ping: 1 });
175
- console.log("Successfully connected to Atlas.");
176
- // your code after this comment
177
157
178
- // your code before this comment
158
+ const database = client.db('sample_mflix');
159
+ const collection = database.collection('movies');
160
+
161
+ // Query for a movie that has the title 'Back to the Future'
162
+ const query = { title: 'Back to the Future' };
163
+ const movie = await collection.findOne(query);
164
+
165
+ console.log(movie);
179
166
} finally {
180
167
// Ensures that the client will close when you finish/error
181
168
await client.close();
182
169
}
183
170
}
184
171
run().catch(console.dir);
185
172
186
- Run the script with the following command from your terminal :
173
+ Run the sample code with the following command from your command line :
187
174
188
- .. code-block:: sh
175
+ .. code-block:: none
189
176
190
177
node index.js
191
178
192
- You should see the output **Successfully connected to Atlas.**
179
+ When you run the command, the sample code should output the details of the
180
+ movie which resembles the following:
181
+
182
+ ::
183
+
184
+ {
185
+ _id: ...,
186
+ plot: 'A young man is accidentally sent 30 years into the past...',
187
+ genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ],
188
+ ...
189
+ title: 'Back to the Future',
190
+ ...
191
+ }
192
+
193
+ If or receive an error, check whether you included the proper connection
194
+ string in the application code, and loaded the sample dataset in your Atlas
195
+ cluster.
196
+
197
+ After completing this step, you should have a working application that uses
198
+ the Node.js driver to connect to your MongoDB instance, run a query on the
199
+ sample data, and prints out the result.
193
200
194
201
Next Steps
195
202
----------
196
203
197
- Learn how to read and modify data in our :doc:`CRUD fundamentals
198
- </fundamentals/crud>` guide, or how to perform common operations in our
199
- :doc:`usage examples </usage-examples>`.
204
+ Learn how to read and modify data using the Node.js driver in our
205
+ :doc:`CRUD fundamentals </fundamentals/crud>` guide, or how to perform common
206
+ operations from our :doc:`usage examples </usage-examples>`.
0 commit comments