UNPKG

15.1 kBMarkdownView Raw
1# MongoDB NodeJS Driver
2
3[![npm](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/)
4
5The official [MongoDB](https://www.mongodb.com/) driver for Node.js.
6
7**NOTE: v3.x released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).**
8
9## Version 4.0
10
11**Looking for the latest?** We're working on the next major version of the driver, now in beta.
12Check out our [beta version 4.0 here](https://github.com/mongodb/node-mongodb-native/tree/4.0), which includes a full migration of the driver to TypeScript.
13
14## Quick Links
15
16| what | where |
17| ------------- | ---------------------------------------------------- |
18| documentation | http://mongodb.github.io/node-mongodb-native |
19| api-doc | http://mongodb.github.io/node-mongodb-native/3.6/api |
20| source | https://github.com/mongodb/node-mongodb-native |
21| mongodb | http://www.mongodb.org |
22
23### Bugs / Feature Requests
24
25Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a
26case in our issue management tool, JIRA:
27
28- Create an account and login [jira.mongodb.org](https://jira.mongodb.org).
29- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE).
30- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it.
31
32Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the
33Core Server (i.e. SERVER) project are **public**.
34
35### Support / Feedback
36
37For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](https://docs.mongodb.com/manual/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [MongoDB Community Forums](https://community.mongodb.com/tags/c/drivers-odms-connectors/7/node-js-driver).
38
39### Change Log
40
41Change history can be found in [`HISTORY.md`](HISTORY.md).
42
43### Compatibility
44
45For version compatibility matrices, please refer to the following links:
46
47- [MongoDB](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-mongodb-node)
48- [NodeJS](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-language-node)
49
50## Installation
51
52The recommended way to get started using the Node.js driver is by using `npm` (Node Package Manager) to install the dependency in your project.
53
54## MongoDB Driver
55
56Given that you have created your own project using `npm init` we install the MongoDB driver and its dependencies by executing the following `npm` command.
57
58```bash
59npm install mongodb --save
60```
61
62This will download the MongoDB driver and add a dependency entry in your `package.json` file.
63
64You can also use the [Yarn](https://yarnpkg.com/en) package manager.
65
66## Troubleshooting
67
68The MongoDB driver depends on several other packages. These are:
69
70- [bson](https://github.com/mongodb/js-bson)
71- [bson-ext](https://github.com/mongodb-js/bson-ext)
72- [kerberos](https://github.com/mongodb-js/kerberos)
73- [mongodb-client-encryption](https://github.com/mongodb/libmongocrypt#readme)
74
75The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the `kerberos` module. Furthermore, the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install.
76
77**Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.**
78
79### Diagnosing on UNIX
80
81If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps.
82
83```bash
84git clone https://github.com/mongodb-js/kerberos
85cd kerberos
86npm install
87```
88
89If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install `node-gyp` globally:
90
91```bash
92npm install -g node-gyp
93```
94
95If it correctly compiles and runs the tests you are golden. We can now try to install the `mongod` driver by performing the following command.
96
97```bash
98cd yourproject
99npm install mongodb --save
100```
101
102If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode.
103
104```bash
105npm --loglevel verbose install mongodb
106```
107
108This will print out all the steps npm is performing while trying to install the module.
109
110### Diagnosing on Windows
111
112A compiler tool chain known to work for compiling `kerberos` on Windows is the following.
113
114- Visual Studio C++ 2010 (do not use higher versions)
115- Windows 7 64bit SDK
116- Python 2.7 or higher
117
118Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`.
119
120```bash
121npm install -g node-gyp
122```
123
124Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild:
125
126```bash
127git clone https://github.com/christkv/kerberos.git
128cd kerberos
129npm install
130node-gyp rebuild
131```
132
133This should rebuild the driver successfully if you have everything set up correctly.
134
135### Other possible issues
136
137Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there).
138
139Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed.
140
141## Quick Start
142
143This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [tutorials](docs/reference/content/tutorials/main.md).
144
145### Create the `package.json` file
146
147First, create a directory where your application will live.
148
149```bash
150mkdir myproject
151cd myproject
152```
153
154Enter the following command and answer the questions to create the initial structure for your new project:
155
156```bash
157npm init
158```
159
160Next, install the driver dependency.
161
162```bash
163npm install mongodb --save
164```
165
166You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory.
167
168### Start a MongoDB Server
169
170For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/).
171
1721. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads)
1732. Create a database directory (in this case under **/data**).
1743. Install and start a `mongod` process.
175
176```bash
177mongod --dbpath=/data
178```
179
180You should see the **mongod** process start up and print some status information.
181
182### Connect to MongoDB
183
184Create a new **app.js** file and add the following code to try out some basic CRUD
185operations using the MongoDB driver.
186
187Add code to connect to the server and the database **myproject**:
188
189```js
190const MongoClient = require('mongodb').MongoClient;
191const assert = require('assert');
192
193// Connection URL
194const url = 'mongodb://localhost:27017';
195
196// Database Name
197const dbName = 'myproject';
198const client = new MongoClient(url);
199// Use connect method to connect to the server
200client.connect(function(err) {
201 assert.equal(null, err);
202 console.log('Connected successfully to server');
203
204 const db = client.db(dbName);
205
206 client.close();
207});
208```
209
210Run your app from the command line with:
211
212```bash
213node app.js
214```
215
216The application should print **Connected successfully to server** to the console.
217
218### Insert a Document
219
220Add to **app.js** the following function which uses the **insertMany**
221method to add three documents to the **documents** collection.
222
223```js
224const insertDocuments = function(db, callback) {
225 // Get the documents collection
226 const collection = db.collection('documents');
227 // Insert some documents
228 collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }], function(err, result) {
229 assert.equal(err, null);
230 assert.equal(3, result.result.n);
231 assert.equal(3, result.ops.length);
232 console.log('Inserted 3 documents into the collection');
233 callback(result);
234 });
235};
236```
237
238The **insert** command returns an object with the following fields:
239
240- **result** Contains the result document from MongoDB
241- **ops** Contains the documents inserted with added **\_id** fields
242- **connection** Contains the connection used to perform the insert
243
244Add the following code to call the **insertDocuments** function:
245
246```js
247const MongoClient = require('mongodb').MongoClient;
248const assert = require('assert');
249
250// Connection URL
251const url = 'mongodb://localhost:27017';
252
253// Database Name
254const dbName = 'myproject';
255
256// Use connect method to connect to the server
257MongoClient.connect(url, function(err, client) {
258 assert.equal(null, err);
259 console.log('Connected successfully to server');
260
261 const db = client.db(dbName);
262
263 insertDocuments(db, function() {
264 client.close();
265 });
266});
267```
268
269Run the updated **app.js** file:
270
271```bash
272node app.js
273```
274
275The operation returns the following output:
276
277```bash
278Connected successfully to server
279Inserted 3 documents into the collection
280```
281
282### Find All Documents
283
284Add a query that returns all the documents.
285
286```js
287const findDocuments = function(db, callback) {
288 // Get the documents collection
289 const collection = db.collection('documents');
290 // Find some documents
291 collection.find({}).toArray(function(err, docs) {
292 assert.equal(err, null);
293 console.log('Found the following records');
294 console.log(docs);
295 callback(docs);
296 });
297};
298```
299
300This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback:
301
302```js
303const MongoClient = require('mongodb').MongoClient;
304const assert = require('assert');
305
306// Connection URL
307const url = 'mongodb://localhost:27017';
308
309// Database Name
310const dbName = 'myproject';
311
312// Use connect method to connect to the server
313MongoClient.connect(url, function(err, client) {
314 assert.equal(null, err);
315 console.log('Connected correctly to server');
316
317 const db = client.db(dbName);
318
319 insertDocuments(db, function() {
320 findDocuments(db, function() {
321 client.close();
322 });
323 });
324});
325```
326
327### Find Documents with a Query Filter
328
329Add a query filter to find only documents which meet the query criteria.
330
331```js
332const findDocuments = function(db, callback) {
333 // Get the documents collection
334 const collection = db.collection('documents');
335 // Find some documents
336 collection.find({ a: 3 }).toArray(function(err, docs) {
337 assert.equal(err, null);
338 console.log('Found the following records');
339 console.log(docs);
340 callback(docs);
341 });
342};
343```
344
345Only the documents which match `'a' : 3` should be returned.
346
347### Update a document
348
349The following operation updates a document in the **documents** collection.
350
351```js
352const updateDocument = function(db, callback) {
353 // Get the documents collection
354 const collection = db.collection('documents');
355 // Update document where a is 2, set b equal to 1
356 collection.updateOne({ a: 2 }, { $set: { b: 1 } }, function(err, result) {
357 assert.equal(err, null);
358 assert.equal(1, result.result.n);
359 console.log('Updated the document with the field a equal to 2');
360 callback(result);
361 });
362};
363```
364
365The method updates the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Next, update the callback function from **MongoClient.connect** to include the update method.
366
367```js
368const MongoClient = require('mongodb').MongoClient;
369const assert = require('assert');
370
371// Connection URL
372const url = 'mongodb://localhost:27017';
373
374// Database Name
375const dbName = 'myproject';
376
377// Use connect method to connect to the server
378MongoClient.connect(url, function(err, client) {
379 assert.equal(null, err);
380 console.log('Connected successfully to server');
381
382 const db = client.db(dbName);
383
384 insertDocuments(db, function() {
385 updateDocument(db, function() {
386 client.close();
387 });
388 });
389});
390```
391
392### Remove a document
393
394Remove the document where the field **a** is equal to **3**.
395
396```js
397const removeDocument = function(db, callback) {
398 // Get the documents collection
399 const collection = db.collection('documents');
400 // Delete document where a is 3
401 collection.deleteOne({ a: 3 }, function(err, result) {
402 assert.equal(err, null);
403 assert.equal(1, result.result.n);
404 console.log('Removed the document with the field a equal to 3');
405 callback(result);
406 });
407};
408```
409
410Add the new method to the **MongoClient.connect** callback function.
411
412```js
413const MongoClient = require('mongodb').MongoClient;
414const assert = require('assert');
415
416// Connection URL
417const url = 'mongodb://localhost:27017';
418
419// Database Name
420const dbName = 'myproject';
421
422// Use connect method to connect to the server
423MongoClient.connect(url, function(err, client) {
424 assert.equal(null, err);
425 console.log('Connected successfully to server');
426
427 const db = client.db(dbName);
428
429 insertDocuments(db, function() {
430 updateDocument(db, function() {
431 removeDocument(db, function() {
432 client.close();
433 });
434 });
435 });
436});
437```
438
439### Index a Collection
440
441[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's
442performance. The following function creates an index on the **a** field in the
443**documents** collection.
444
445```js
446const indexCollection = function(db, callback) {
447 db.collection('documents').createIndex({ a: 1 }, null, function(err, results) {
448 console.log(results);
449 callback();
450 });
451};
452```
453
454Add the `indexCollection` method to your app:
455
456```js
457const MongoClient = require('mongodb').MongoClient;
458const assert = require('assert');
459
460// Connection URL
461const url = 'mongodb://localhost:27017';
462
463const dbName = 'myproject';
464
465// Use connect method to connect to the server
466MongoClient.connect(url, function(err, client) {
467 assert.equal(null, err);
468 console.log('Connected successfully to server');
469
470 const db = client.db(dbName);
471
472 insertDocuments(db, function() {
473 indexCollection(db, function() {
474 client.close();
475 });
476 });
477});
478```
479
480For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md).
481
482## Next Steps
483
484- [MongoDB Documentation](http://mongodb.org)
485- [Read about Schemas](http://learnmongodbthehardway.com)
486- [Star us on GitHub](https://github.com/mongodb/node-mongodb-native)
487
488## License
489
490[Apache 2.0](LICENSE.md)
491
492© 2009-2012 Christian Amor Kvalheim
493© 2012-present MongoDB [Contributors](CONTRIBUTORS.md)